头文件< set >
元素在插入时自动排序
底层实现也是红黑树
set
不允许有重复元素
插入
set<int> a;
a.insert(10);
a.insert(120);
a.insert(60);
a.insert(60);
a.insert(40);
/*拷贝构造*/
set<int>b(a);
/*赋值*/
set<int>c;
c = b;
for (set<int>::iterator it = c.begin(); it != c.end(); it++)
{
cout << *it << endl;
}
发现重复的值不会被插入
set<int> a;
pair<set<int>::iterator,bool> res = a.insert(60);
pair<set<int>::iterator, bool> res1 = a.insert(60);
a.insert(40);
cout << "第一个60:" << res.second << endl;//插入成功
cout << "第二个60:" << res1.second << endl;//插入失败
size()(获取set中元素数目)
cout<<a.set();//4
erase()(删除set中元素)
a.erase(a.begin());//删除排序后的第一个元素
a.erase(40);//指定删除哪个值
a.erase(a.begin(),a.end());//删除一个区间
count()(统计元素个数)
int num = a.count(30);//只有0或者1 因为不存在重复值
find()(查找key是否存在 不存在返回set.end())
返回的是迭代器
//cout<<a.end();//这样是不行的
set<int>::iterator pos = a.find(5);
if (pos != a.end())
{
cout << "找到了" << endl;
}
改变排序规则
仿函数本质上是一个数据类型
/*仿函数*/
class myCompare {
public:
bool operator()(int v1, int v2) const
{
return v1 > v2;
}
};
int main()
{
set<int,myCompare> a;
a.insert(20);
a.insert(60);
a.insert(40);
for (set<int, myCompare>::iterator it = a.begin(); it != a.end(); it++)
{
cout << *it << endl;
}
}
添加自定义数据
这样会报错 因为没办法自动排序 所以要写一个仿函数
class P
{
public:
P(string x, int y)
{
a = x;
num = y;
}
string a;
int num;
};
int main()
{
set<P> a;
P x("张三", 3);
P y("李四", 4);
P z("王五", 5);
a.insert(x);
a.insert(y);
a.insert(z);
multiset
允许有重复的元素
multiset<int> a;
a.insert(10);
a.insert(120);
a.insert(60);
a.insert(60);
a.insert(40);
/*拷贝构造*/
multiset<int>b(a);
/*赋值*/
multiset<int>c;
c = b;
for (multiset<int>::iterator it = c.begin(); it != c.end(); it++)
{
cout << *it << endl;
}