C++-set

头文件< 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;
	}

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值