특징
데이터를 정렬해 주면서 저장.
중복된 값을 저장하지 않는다. ( 중복 허용: multiset )
두번째 인자로 정렬 형태를 지정한다.
원소의 위치가 명확하지 않기 때문에 push.back() 함수를 사용할 수 없다.
반복자는 내부구조에 상관없이 사용 가능하다.
1. 선언
정수의 set 이라면 std::set<int> setSort; 선언
만약 custom type set 이라면
set<customeType, lessFunctionClass> setCustomType;
선언한다.
lessFunctionClass
: customeType의 데이터의 대소관계, 즉 '<'관계를 bool 형태로 반환하는 operator()를 멤버 함수로 가지는 class
일반적으로 대소관계가 정의되어 있는 타입 int, double, char ... 아니라면 대소 관계를 알 수 없기에 중복여부를 체크할 수가 없게 된다.
So, set에는 대소관계를 정의한 class를 두번째 Template Class 로 주어야 한다.
class lessFunctionClass
{
public:
lessFunctionClass() { }
~lessFunctionClass() { }
bool operator()(const customType & lhsCustomType, const customType & rhsCustomType)
{
// return true if lhsCustomType is less than rhsCustomType
// otherwise, return false
}
};
클래스 외 구조체로도 정의 가능
struct ltstr
{
bool operator()( const char* s1, const char* s2 ) const
{
return strcmp(s1, s2) < 0;
}
};
set<const char*, ltstr> A;
2. 데이터의 추가
CustomType customeTypeData;
set<CustomType, LessFunctionClass> sCustomType;
// 데이터 추가
sCustomType.insert(customTypeData);
3. 데이터의 삭제
CustomType customTypeData;
set<CustomType, LessFunctionClass> sCustomType;
set<CustomType, LessFunctionClass>::iterator itCustomType;
// 데이터를 찾아서 해당 데이터에 대한 포인터를 iterator 로 받음.
itCustomType = sCustomType.find(customTypeData);
// iterator 가 end() 와 다르면, 데이터가 있단 뜻.
if (itCustomType != sCustomType.end())
{
// 데이터를 지움.
sCustomType.erase(itCustomType);
}
사용법
#include <set>
using namespace std;
void main()
{
std::set<int> setSort; //오름차순정렬
// std::set<int, greater<int>, allocator<int> > setSort; //내림차순정렬
//임의의 순서대로 삽입
setSort.insert(3);
setSort.insert(1);
setSort.insert(5);
setSort.insert(5);
std::set<int>::const_iterator pos;
for(pos = setSort.begin(); pos != setSort.end(); ++pos)
printf("*pos ");
}
//출력
//1 3 5
추가 MultiSet 사용법
#include <set>
using namespace std;
void main( )
{
multiset<int> s;
s.insert( 50 );
s.insert( 50 );
s.insert( 10 );
s.insert( 80 );
s.insert( 80 );
s.insert( 80 );
s.insert( 30 );
s.insert( 70 );
s.insert( 60 );
multiset<int>::iterator iter;
for( iter = s.begin(); iter != s.end() ; iter++)
cout << *iter << ' ';
cout << endl;
pair<multiset<int>::iterator, multiset<int>::iterator > iter_pair;
iter_pair = s.equal_range( 80 );
for( iter = iter_pair.first ; iter != iter_pair.second ; iter++)
cout << *iter << ' ';
cout << endl;
}
출력
10 30 50 50 60 70 80 80 80
80 80 80
equal_range() 함수를 사용하면 찾은 데이터의 구간 반복자 쌍을 얻을 수 있다.
rickd.egloos.com/4893015 |작성자 요이나
blog.naver.com/yoina5173?Redirect=Log&logNo=150003217081 |작성자 릭디아스
blog.daum.net/coolprogramming/82 |작성자 NetGong
'[ Programing ] > STL & Booster' 카테고리의 다른 글
[BOOST] BOOST_FOREACH (0) | 2010.08.30 |
---|---|
[STL] 다중 정렬시 주로 사용 하는 stable_sort() (0) | 2010.08.24 |
[STL] Binary search ( qsort, bsearch ) (0) | 2010.06.29 |
[STL] Map, MultiMap 삽입, 검색, 삭제 (3) | 2010.01.31 |
[STL] sort( vecStock.begin(), vecStock.end(), SortCredit ); 정렬 (0) | 2010.01.31 |