轉自:http://www.cnblogs.com/graphics/archive/2010/06/01/1749569.html
set是一種隨機存儲的關聯式容器,其關鍵詞(key)和元素(value)是同一個值。set之中所有元素互不相同。set是通過二叉查找樹來實現的。
創建一個空的set
1: set<> s0 ;
創建一個帶大於比較器的set, 默認是小於比較器less<int>
1: set<, greater<>> s1 ;
用數組初始化一個set
1: a[3] = {1, 2, 3} ;
2: set<> s2(a, a + 3) ;
用拷貝構造函數初始化set
1: set<> s1 ;
2: set<> s2(s1) ;
區間初始化
1: set<> s1 ;
2: set<> s2(s1.begin(), s1.end()) ;
自定義比較函數
以類為比較器
1: classcmp
2: {
3: ()( & lhs, & rhs)
4: {
5: lhs < rhs ;
6: }
7: };
8:
9: main()
10: {
11: set<, classcmp> s5 ;
12:
13: system("") ;
14: 0 ;
15: }
以函數指針為比較器
1: fncmp( lhs, rhs)
2: {
3: lhs < rhs ;
4: }
5:
6: main()
7: {
8: (*fn_pt)(, ) = fncmp ;
9: set<, (*)(, )> s1(fn_pt) ;
10:
11: system("") ;
12: 0 ;
13: }
1: a[3] = {1, 2, 3} ;
2: set<> s(a, a + 3) ;
3:
4: set<>::const_iterator itor ;
5: itor = s.begin() ;
6:
7: (itor != s.end())
8: {
9: cout << *itor << endl ;
10: ++itor ;
11: }
1: a[3] = {1, 2, 3} ;
2: set<> s(a, a + 3) ;
3:
4: set<>::const_iterator itor ;
5: (itor = s.begin(); itor != s.end(); ++itor)
6: {
7: cout << *itor << endl ;
8: }
1: a[3] = {1, 2, 3} ;
2: set<> s(a, a + 3) ;
3:
4: set<>::const_reverse_iterator ritor ;
5: ritor = s.rbegin() ;
6:
7: (ritor != s.rend())
8: {
9: cout << *ritor << endl ;
10: ++ritor ;
11: }
1: a[3] = {1, 2, 3} ;
2: set<> s(a, a + 3) ;
3:
4: set<>::const_reverse_iterator ritor ;
5: (ritor = s.rbegin(); ritor != s.rend(); ++ritor)
6: {
7: cout << *ritor << endl ;
8: }
插入單個值
1: set<> s ;
2: s.insert(1) ;
成片插入
1: a[3] = {1, 2, 3} ;
2: set<> s ;
3: s.insert(a, a + 3) ;
1: a[3] = {1, 2, 3} ;
2: set<> s(a, a + 3) ;
3:
4: set<> s1 ;
5: s1.insert(s.begin(), s.end()) ;
1: set<> s ;
2: ( i = 1; i <= 5; ++i)
3: s.insert(i) ;
4:
5: set<>::const_iterator citor ;
6: citor = s.begin() ;
7: ++citor ;
8:
9:
10: s.erase(citor) ;
11:
12:
13: citor = s.find(3) ;
14: s.erase(citor, s.end()) ;
15:
16:
17: s.erase(s.begin(), s.end()) ;
1: set<> s ;
2: ( i = 1; i <= 5; ++i)
3: s.insert(i) ;
4:
5: set<>::iterator itor ;
6: itor = s.find(4) ;
7: (itor != s.end())
8: cout << "" ;
9:
10: cout << "" ;
1: set<> s ;
2: ( i = 1; i <= 5; ++i)
3: s.insert(i) ;
4:
5: set<>::iterator itor ;
6: (s.count(4) == 1)
7: cout << "" ;
8:
9: cout << "" ;
由於set本身是有序的,所以不提供排序函數。