#include <iostream>
#include <set>
#include <string>
using namespace std;
//自定义比较函数 myComp 重载"()"操作符
struct myComp{
bool operator()(int a,int b){
if(a!=b){
return a>b;
}
else{
return a>b;
}
}
};
struct Info
{
string name;
float score;
//重载 < 操作符,自定义排序规则
bool operator < (const Info &a) const
{
//按score从大到小排序。如果从小到大排,使用 > 即可
return a.score<score;
}
};
int main(){
//set 集合容器实现平衡二叉检索树的数据结构
//会自动排序 默认从小到大
set<int> s;
s.insert(8); //插入
s.insert(4);
s.insert(9);
s.insert(8); //由于8重复,第二次插入的8并没有执行
s.insert(5);
//中序遍历集合中的元素
set<int>::iterator it; //定义前向迭代器
for(it=s.begin();it!=s.end();it++){
cout << *it << ' ';
} cout << endl;
//元素的反向遍历
set<int>::reverse_iterator rit;//定义反向迭代器
for(rit=s.rbegin();rit!=s.rend();rit++){
cout <<*rit << " ";
} cout << endl;
//元素的删除
s.erase(9); //删除键值为9的那个元素
for(it=s.begin();it!=s.end();it++){
cout << *it << ' ';
} cout << endl;
// s.clear();//清空集合
// cout << s.size() << endl;
//元素的检索
it=s.find(8); //查找键值为8的元素
if(it!=s.end()){
cout << *it << endl; //找到
}
else{
cout <<"not find it" << endl; //没找到
}
//自定义比较函数
set<int,myComp> a;
a.insert(5);
a.insert(8);
a.insert(7);
a.insert(8);//重复 无效
a.insert(2);
set<int,myComp>::iterator i;//定义前向迭代器
for(i=a.begin();i!=a.end();i++){
cout << *i << ' ';
} cout << endl;
//元素是结构体 直接把比较函数写在结构体内
set<Info> f;
Info info;
//插入3个元素
info.name="John" ;
info.score=80.5;
f.insert(info);
info.name="Jake";
info.score=90.5;
f.insert(info);
info.name="Tom";
info.score=65.3;
f.insert(info);
set<Info>::iterator j;//定义前向迭代器
for(j=f.begin();j!=f.end();j++){
cout << (*j).name << ' ' << (*j).score << endl;
} cout << endl;
return 0;
}
set集合容器
最新推荐文章于 2022-12-01 11:57:39 发布