2017-08-20 15:21:31
writer:pprp
set集合容器使用红黑树的平衡二叉树检索树,不会将重复键值插入,检索效率高 logn
检索使用中序遍历,所以可以将元素从小到大排列出来
/* name : usage of Set writer : pprp declare : null date ; 2017/8/20 */ #include <bits/stdc++.h> using namespace std; void print(set<int> &s) { set<int>::iterator it; for(it = s.begin(); it != s.end(); it++) { cout << *it <<" "; } cout << endl; } void printms(multiset<int> &ms) { set<int>::iterator it; for(it = ms.begin() ; it != ms.end() ; it++) { cout << *it << " "; } cout << endl; } int main() { set<int> s; //set的建立 for(int i = 0 ; i <= 10 ; i++) { pair<set<int>::iterator, bool> p = s.insert(i);//用于判断是否插入成功 if(p.second) cout << "successful" << endl; else cout << "can not insert the same word" << endl; } set<int> s2(s);//初始化 print(s2); s2.erase(s2.begin()); //只把头删除了 print(s2); s2.erase(s2.erase(10)); //把头和值位10的点都删除了 print(s2); //完成对某个元素的查找 set<int>::iterator i; i = s2.find(5); if(i != s2.end()) { cout << "find" << endl; } else cout << "can not find" << endl; //测试是否可重复 multiset<int> ms; for(int i = 0 ; i <= 20 ; i = i + 2) { ms.insert(i); ms.insert(i+2); ms.insert(i+3); ms.insert(i+4); } //测试是否有序 ms.insert(-1); ms.insert(100); printms(ms); //查找元素 int v = 8; multiset<int>::iterator t = ms.find(v); if(t != ms.end()) { cout << *t << endl; } //查找相同元素 pair<multiset<int>::iterator,multiset<int>::iterator> cmp = ms.equal_range(v); cout << *cmp.first << endl; //第一个大于等于该元素的值 cout << *cmp.second << endl; //第一个大于该元素的值 cout << ms.count(6) << endl;//集合中元素为6的个数 multiset<int>::iterator ii; ii = ms.lower_bound(8); cout << *ii << endl; ii = ms.upper_bound(8); cout << *ii << endl; return 0; }
时间: 2024-12-05 08:59:42