STL中的set
set关联式容器:set作为一个容器也是用来存储同一数据类型的数据类型,并且能从一个数据集合中取出数据,在set中每个元素的值都唯一,而且系统能根据元素的值自动进行排序(升序排列)。set中元素的值不能在容器中修改(元素总是常量),但是可以从容器中插入或删除它们(不能直接修改容器内数据,所以只能删除某元素再插入要修改的数值)。
关联容器:元素按照关键字来保存和访问,STL中的map,set就是关联容器
声明:template <class Key, class Compare=less<Key>, class Alloc=STL_DEFAULT_ALLOCATOR(Key) > //Key为元素(键值)类型 greater是从升序排序(默认),可以改为less(降序排序)
map和set的插入删除效率比用其他序列容器高
1.set基本使用方法:
- iterator insert(T) 向集合中插入一个元素
- begin() ,返回set容器的第一个迭代器
- end() ,返回set容器的最后一个迭代器
- clear() ,删除set容器中的所有的元素
- empty() ,判断set容器是否为空
- max_size() ,返回set容器可能包含的元素最大个数
- size() ,返回当前set容器中的元素个数
- rbegin ,返回的值和end()相同
- rend() ,返回的值和rbegin()相同
1 #include <iostream>
2 #include <set>
3
4 using namespace std;
5
6 int main()
7 {
8 set<int> s;
9 s.insert(1);
10 s.insert(2);
11 s.insert(3);
12 s.insert(1);
13 cout<<"set 的 size 值为 :"<<s.size()<<endl;
14 cout<<"set 的 maxsize的值为 :"<<s.max_size()<<endl;
15 cout<<"set 中的第一个元素是 :"<<*s.begin()<<endl;
16 cout<<"set 中的最后一个元素是:"<<*s.end()<<endl;
17 s.clear();
18 if(s.empty())
19 {
20 cout<<"set 为空 !!!"<<endl;
21 }
22 cout<<"set 的 size 值为 :"<<s.size()<<endl;
23 cout<<"set 的 maxsize的值为 :"<<s.max_size()<<endl;
24 return 0;
25 }
2. 查找
1 //s.find() 查找一个元素,如果容器中不存在该元素,返回值等于s.end()
2 #include <iostream>
3 #include <set>
4 using namespace std;
5 set<int >s;
6 void setprint(int cnt){
7 cout << "Test output :" << cnt << ":" << endl;
8 for(set<int>::iterator it = s.begin(); it!= s.end(); it++)
9 cout << *it << " ";
10 puts("");
11 return ;
12 }
13 int main(){
14 int cnt = 1;
15 s.insert(1);
16 s.insert(2);
17 s.insert(5);
18 setprint(cnt++);
19 if(s.find(2) != s.end())
20 cout << "2 is existent" << endl;
21 else
22 cout << "2 is non-existent" << endl;
23 if(s.find(3) == s.end())
24 cout << "3 is non-existent" << endl;
25 else
26 cout << "2 is existent" << endl;
27 return 0;
28 }
3.set 的其他常用操作展开:
s.lower_bound(); 返回第一个大于或等于给定关键值的元素
s.upper_bound(); 返回第一个大于给定关键值的元素
s.equal_range(); 返回一对定位器,分别表示 第一个大于或等于给定关键值的元素 和 第一个大于给定关键值的元素,这个返回值是一个 pair 类型,如果这一对定位器中哪个返回失败,就会等于 s.end()
1 #include <iostream>
2 #include <set>
3 using namespace std;
4 int main(){
5 set<int> s;
6 s.insert(1);
7 s.insert(2);
8 s.insert(5);
9 cout << "lower_bound & upper_bound test:" << endl;
10 cout << "第一个大于或等于3的元素: " << *s.lower_bound(3) << endl;
11 cout << "第一个大于或等于2的元素: " <<*s.lower_bound(2) << endl;
12 cout << "第一个大于2的元素: " <<*s.upper_bound(2) << endl;
13 cout << "equal_range test:" << endl;
14 cout << "第一个大于或等于2的元素: " << *s.equal_range(2).first << endl;
15 cout << "第一个大于2的元素: " << *s.equal_range(2).second << endl;
16 return 0;
17 }
1 //判断元素是否在set中 & 判断set是否为空
2 #include <iostream>
3 #include <set>
4 #include <functional>
5 using namespace std;
6 int main(){
7 set<int > s;
8 if(s.empty()) cout << "容器为空" << endl;
9 s.insert(1);
10 if(!s.empty()) cout << "容器不为空" << endl;
11 if(s.count(1)) cout << "1在容器中" << endl;
12 if(!s.count(2)) cout << "2不在容器中" << endl;
13 return 0;
14 }