Set集合常用操作

1) 元素插入:

insert()

2) 中序遍历:

类似vector遍历(用迭代器)

3) 反向遍历:

利用反向迭代器reverse_iterator。

<pre name="code" class="html"><pre name="code" class="cpp">set<int> s;
......
set<int>::reverse_iterator rit;
for(rit=s.rbegin();rit!=s.rend();rit++)
 
 


4) 元素删除:

与插入一样,可以高效的删除,并自动调整使红黑树平衡。

set<int> s;
s.erase(2);        //删除键值为2的元素
s.clear();


5) 元素检索:

find(),若找到,返回该键值迭代器的位置,否则,返回最后一个元素后面一个位置。

set<int> s;
set<int>::iterator it;
it=s.find(5);    //查找键值为5的元素
if(it!=s.end())    //找到
	cout<<*it<<endl;
else cout<<"未找到";

6) 自定义比较函数:

(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;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值