1.set基本用法
#include<iostream>
#include<set>
using namespace std;
//打印
void printSet(set<int>&s){
for(set<int>::iterator it=s.begin();it!=s.end();it++){
cout<<*it<<" ";
}
cout<<endl;
}
int main(){
//有序集合
set<int>s;
//无序集合 区别在于插入函数会返回两个值
multiset<int>ms;
//插入
s.insert(1);
s.insert(10);
s.insert(4);
//删除--erase 两种:指定元素 指定迭代器范围
//s.erase(10);
s.erase(s.begin());
//查找指定元素x--find(x),找到返回迭代器,没找到返回s.end()
if(s.find(10)!=s.end()){
cout<<"找到了"<<*s.find(10)<<endl;
}else{
cout<<"没找到"<<endl;
}
//二分查找--查找大于等于/大于x,返回迭代器
set<int>::iterator l1=s.lower_bound(4);
set<int>::iterator l2=s.upper_bound(4);
cout<<"大于等于4:"<<*l1<<" 大于4:"<<*l2<<endl;
//insert(x)返回结果有两个,第一个元素是插入元素的迭代器,第二个是bool值
pair<set<int>::iterator,bool>p = s.insert(20);
if(p.second){
cout<<*(p.first)<<"插入成功!"<<endl;
}else{
cout<<*(p.first)<<"插入失败!"<<endl;
}
printSet(s);
}
2.set与类
#include<iostream>
#include<set>
#include<string>
using namespace std;
class Person{
public:
string name;
int age;
Person(string s1,int age):name(s1),age(age){}
// Person(string s1,int age){
// this->name = s1;
// this->age = age;
// }
};
class MyCompare1{
public:
bool operator()(int x,int y)const{
return x>y;
}
};
class MyCompare2{
public:
bool operator()(const Person &p1,const Person &p2)const{
return p1.age>p2.age;
}
};
int main(){
set<int,MyCompare1>s = {1,2,4};
for(set<int,MyCompare1>::iterator it=s.begin();it!=s.end();it++){
cout<<*it<<" ";
}
//类
Person p1 = {"yzq",12};
Person p2 = {"yzq",16};
Person p3 = {"yzq",18};
set<Person,MyCompare2>p;
p.insert(p1);
p.insert(p2);
p.insert(p3);
for(set<Person,MyCompare2>::iterator it=p.begin();it!=p.end();it++){
cout<<it->name<<" "<<it->age<<endl;
}
}