set
集合容器:实现了红黑树的平衡二叉的数据结构,插入元素时,会自动调整二叉树的排列,把元素放到适当的位置,用以保证每个子树根节点键值大于左子树,小于右子树所有节点的键值,并且还保证根节点左子树高度与右子树高度相等。因此检索效率高于,vector,list和deque。另外,其还有从小到大的排序功能。(当用set类装自定义类时,要重载小于号)
常用操作
- insert() //插入
s.insert(i)
- 删除erase()
- -
- 清空clear()
- 元素个数size()
- 检索find()与conunt()
- “
- 中序遍历:类比vector(从小到大排列)
- 还可以反向便利,(从大到小)利用rbeing()和rend()
- -
练习实践代码
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <iterator>
#include <set>
typedef struct retangle{
int num;
int wid;
int len;
}ret;
using namespace std;
bool operator<(const ret & r1,const ret & r2){
return r1.num < r2.num;
}
istream & operator>>(istream & in, ret & r){
in >> r.num;
int a,b;
cin >> a >> b;
r.len = max(a,b);
r.wid = min(a,b);
return in;
}
ostream & operator<<(ostream & out,const ret & r){
return out << r.num << r.len << r.wid;
}
int main(){
set<int> s;//建立集合类
for(int i = 0;i < 10; ++i){
s.insert(i);//插入元素
}
copy(s.begin(),s.end(),ostream_iterator<int>(cout," "));//将集合类输出
cout << endl;
//删除集合类元素5
s.erase(5);
cout << "删除集合类元素5" << endl;
copy(s.begin(),s.end(),ostream_iterator<int>(cout," "));
cout << endl;
cout << "检查集合元素5是否存在 " << s.count(5) << endl;
cout << "检查集合元素4是否存在 " << s.count(4) << endl;
cout << "查找集合元素7,并且输出" << endl;
set<int>::iterator it;
it = s.find(7);
if(it != s.end()){
cout << "exist" << *it << endl;
}else{
cout << "no exist" << endl;
}
cout << "s.clear" << endl;
s.clear();
cout << "size" << s.size() << endl;
//测试结构体类型,需要从载比较函数。 ,输入输出函数
freopen("C:\\Users\\creator\\Desktop\\input.txt","r",stdin);
int zu;
cin >> zu;
while(zu--){
set<ret> group;
int number;
cin >> number;
ret temp;
while(number--){
cin >> temp;
group.insert(temp);
}
copy(group.begin(),group.end(),ostream_iterator<ret>(cout,"\n"));
}
}