set集合容器

#include <iostream>
#include <set> 
#include <string>
using namespace std;

//自定义比较函数 myComp 重载"()"操作符 
struct myComp{
	bool operator()(int a,int b){
		if(a!=b){
			return a>b;
		}
		else{
			return a>b;
		}
	}
}; 

struct Info
{
	string name;
	float score;
	//重载 <  操作符,自定义排序规则
	bool operator < (const Info &a) const
	{
		//按score从大到小排序。如果从小到大排,使用 > 即可 
		return a.score<score;
	} 
	 
};
int main(){
	//set 集合容器实现平衡二叉检索树的数据结构
	//会自动排序 默认从小到大 
	set<int> s;
	s.insert(8);	//插入 
	s.insert(4);
	s.insert(9);
	s.insert(8);	//由于8重复,第二次插入的8并没有执行
	s.insert(5);
	//中序遍历集合中的元素
	set<int>::iterator it; //定义前向迭代器
	for(it=s.begin();it!=s.end();it++){
		cout << *it << ' ';
	} cout << endl;
	
	//元素的反向遍历
	set<int>::reverse_iterator rit;//定义反向迭代器
	for(rit=s.rbegin();rit!=s.rend();rit++){
		cout <<*rit << " "; 
	} cout << endl;
	
	//元素的删除
	s.erase(9);	//删除键值为9的那个元素
	for(it=s.begin();it!=s.end();it++){
		cout << *it << ' ';
	} cout << endl;
//	s.clear();//清空集合
//	cout << s.size() << endl; 
	//元素的检索
	it=s.find(8);	//查找键值为8的元素
	if(it!=s.end()){
		cout << *it << endl;	//找到 
	} 
	else{
		cout <<"not find it" << endl;	//没找到 
	} 
	//自定义比较函数 
	set<int,myComp> a;
	a.insert(5);
	a.insert(8);
	a.insert(7);
	a.insert(8);//重复 无效
	a.insert(2);
	set<int,myComp>::iterator i;//定义前向迭代器
	for(i=a.begin();i!=a.end();i++){
		cout << *i << ' ';
	} cout << endl;
	
	//元素是结构体 直接把比较函数写在结构体内
	set<Info> f;
	Info info;
	//插入3个元素
	info.name="John" ;
	info.score=80.5;
	f.insert(info);
	
	info.name="Jake";
	info.score=90.5;
	f.insert(info);
	
	info.name="Tom";
	info.score=65.3;
	f.insert(info);
	
	set<Info>::iterator j;//定义前向迭代器
	for(j=f.begin();j!=f.end();j++){
		cout << (*j).name << ' ' << (*j).score << endl;
	} cout << endl;
	 
	
	return 0;
	
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值