C++

set使用总结

set/multiset会根据待定的排序准则,==自动将元素排序(默认由小到大)==。两者不同在于前者不允许元素重复,而后者允许。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
set< int > s;
s.insert(s.begin(), 9);
s.insert(1);
s.insert(s.end(),4);
s.insert(5);
s.insert(6);
s.insert(7);
s.insert(9);
s.insert(0);
set< int >::const_iterator itor;
for(itor = s.begin (); itor != s.end(); itor++)
cout<< *itor<<" ";
cout<< endl;
itor = s.find(2); // 关联容器没必要用find算法,因为自带成员函数.find()
//用find算法的写法是:itor = find( s.begin (), s.end (), 2 );
if( itor == s.end() )
cout<< "NOT Found 2!" << endl;
else
cout<< "Found 2 in set!" << endl;
itor = s.find( 5 );
if( itor == s.end() )
cout<< "NOT Found 5!" << endl;
else
cout<< "Found 5 in set!" << endl;
return 0;
}