常用操作:
创建:
set<int> s;
set<int>::iterator it;
插入:
insert() 可以插入单个键值,也可以插入一个容器
例如:s.insert(v.begin(),v.end());
begin() 返回set容器的第一个元素
end() 返回set容器的最后一个元素
大小:
empty() 判断set容器是否为空
max_size() 返回set容器可能包含的元素最大个数
size() 返回当前set容器中的元素个数
rbegin 返回的值和end()相同
rend() 返回的值和rbegin()相同
删除:
clear() 删除set容器中的所有的元素
erase(iterator) 删除定位器iterator指向的值
erase(first,second)删除定位器first和second之间的值
erase(key_value) 删除键值key_value的值
检索:
find() 若找到,返回该键值迭代器的位置,否则,返回最后一个元素后面一个位置。
例如
set<int> s;
set<int>::iterator it;
it=s.find(5); //查找键值为5的元素
if(it!=s.end()) //找到
cout<<*it<<endl;
else //未找到
cout<<"未找到";
lower_bound(key_value) 返回第一个大于等于key_value的定位器
upper_bound(key_value) 返回最后一个大于等于key_value的定位器
自定义比较函数
(1)元素不是结构体:
例:
//自定义比较函数myComp,重载“()”操作符
struct myComp
{
bool operator()(const your_type &a,const your_type &b)
[
return a.data-b.data>0;
}
}
set<int,myComp>s;
......
set<int,myComp>::iterator it;
(2)如果元素是结构体,可以直接将比较函数写在结构体内。
例:
struct Info
{
string name;
float score;
//重载“<”操作符,自定义排序规则
bool operator < (const Info &a) const
{
//按score从大到小排列
return a.score<score;
}
}
set<Info> s;
......
set<Info>::iterator it;