集合
#include<set> using namespace std;
insert()
插入元素
#include<set> #include<string> using namespace std; int main(){ set<string> country; //{} country.insert("China");//{"China"} return 0; }
erase()
删除元素
#include<set> #include<string> using namespace std; int main(){ set<string> country; //{} country.insert("China"); //{"China"} country.erase("China"); //{} return 0; }
count()
判断元素是否存在
#include<set> #include<string> #include<stdio.h> int main(){ set<string> country; country.insert("China"); if(country.count("China")){ cout<< "China belong to country" << endl; } return 0; }
遍历元素
//set<T>::iterator it #include<set> #include<string> #include<iostream> using namespace std; int main(){ set<string> country; country.insert("China"); country.insert("America"); country.insert("France"); for(set<string>::iterator it=country.begin(); it !=country.end();it++){ cout<<*it<<endl; } return 0; }
注:C++中,set遍历是从小到大的。
clear()
清空——会清空set占用的内存
重载运算符
重载<号
#include<iostream> #include<set> using namespace std; struct Point{ int x,y; bool operator <(const Point &rhs)const{ if(x==rhs.x){ return y<rhs.y; }else{ return x<rhs.x; } } }; int main(){ int n; set<Point> v; cin>>n; for(int i=0;i<n;i++){ Point temp; cin >>temp.x >> temp.y; v.insert(temp); } for(set<Point>::iterator it=v.begin(); it!=v.end();it++){ cout<<it->x<<" "it->y<<endl; } }