본문 바로가기

C++ in Windows/STL

set 실습 2

간략한 도서관리 프로그램.

set 실습 여기에서 클래스 추가하고, 내부 조금 수정한 프로그램이다.



#include <iostream>
#include <vector>
#include <set>
#include <string>
#include <sstream>
#include <algorithm>

using namespace std;

class BookCase
{
public:
	string isbn;
	string name;
	string amount;

	BookCase(const string & pIsbn, const string & pName, const string & pAmount )
		: isbn(pIsbn), name(pName), amount(pAmount)	{
	}

	void DataView()	{
		cout << "ISBN : " << isbn << " 도서명 : " << name << " 가격 : " << amount << endl;
	}

	bool operator<(const BookCase &Other) const {
		return isbn < Other.isbn;
	}

	bool operator==(const BookCase& Other) const{
		return (isbn == Other.isbn);
	}
};


void main (void)
{
	set<BookCase> BC;

	BC.insert(BookCase(string("8972804258"), string("Effective C++"), string("12000")));
	BC.insert(BookCase(string("8980545037"), string("More Effective C++"), string("20000")));
	BC.insert(BookCase(string("8956743118"), string("Effective STL"), string("18000")));

	set<BookCase> ::iterator it;

	cout << "기본 데이터 출력" << endl;
	// 데이터 출력.
	for ( it = BC.begin(); it != BC.end(); it++ )
	{
		(*it).DataView();
	}
	
	bool flag = true;

	while(flag)
	{
		string tstr;
		cout << ">> ";
		::getline(cin, tstr);

		
		// command 
		string buf;
		stringstream ss(tstr);

		vector<string> tokens;

		// tokens 에 나눠 담기. " "을 구분자로 한다.
		while ( ss >> buf )
			tokens.push_back(buf);
			
		
		// 나눈 토큰의 양이 0보다 작으면 다시 입력을 받는다.
		if ( tokens.size() <= 0 ) continue;

		// 토큰 커맨드 명령어가 한글자 이상일때.
		if ( tokens[0].length() > 0 )
		{
			char* cmd = new char[tokens[0].length()];
			
			strcpy(cmd , tokens[0].c_str());

			if ( strcmp( cmd, "add") == 0 )	// add일 경우.
			{	
				BC.insert(BookCase(tokens[1].c_str(), tokens[2].c_str(), tokens[3].c_str()));
			}
			else if ( strcmp( cmd, "print") == 0 )
			{
				for ( it = BC.begin(); it != BC.end(); it++ )
				{
					(*it).DataView();
				}
			}
			else if ( strcmp ( cmd, "del") == 0 )
			{
				it = find(BC.begin(), BC.end(), BookCase(tokens[1].c_str(), string(), string()));

				if ( it != BC.end() )
					BC.erase(it);
			}
			else if ( strcmp ( cmd, "find") ==  0 )
			{
				it = find(BC.begin(), BC.end(), BookCase(tokens[1].c_str(), string(), string()));

				if ( it != BC.end() )
				{
					cout << "검색한 책 정보 출력" << endl;
					(*it).DataView();
				}
			}
			else if ( strcmp ( cmd, "end" ) == 0 )
			{
				flag = false;
			}
			else if ( strcmp ( cmd, "/?") == 0 || strcmp ( cmd, "help") == 0 )
			{
				cout << "add {ISBN} {도서명} {가격} = 책 정보 추가" << endl;
				cout << "del {ISBN} = 책 정보 삭제" << endl;
				cout << "find {ISBN} = 책 검색" << endl;
				cout << "print = 책장 출력" << endl;
				cout << "end = 프로그램 종료" << endl;
			}
		}
	}
}


set 컨테이너는 데이터가 추가되면, 내부적으로 자동으로 정렬을 한다.
정렬은 어떤 데이터의 크기(무게)에 따라 순차적으로 배열하는 것이다. 
그러니 정렬을 위해선 어떤 값이 큰지 작은지를 비교를 해야한다.

위 코드에서는 BookCase라는 책장 클래스를 만들어 set 컨테이너에 넣고
자동으로 정렬이 되기 위해 < 연산자를 오버라이딩 해주었다.


== 연산자를 오버라이딩한 이유는 algorithm의 find를 사용하기 위해서 이다.


참고로 set컨테이너에서 키값이 되는건 중복으로 들어가지 않는다.


set 컨테이너의 키값이 무결성을 잃어버리면, 이후 set 컨테이너는 제대로 동작하지 않는다.

검색, 삽입, 삭제도 예측 할 수 없게 된다.




'C++ in Windows > STL' 카테고리의 다른 글

set 실습  (2) 2012.07.09
vector 실습  (0) 2012.07.04