map和set容器自定义比较函数

将元素插入map和set中时,容器会根据设定的比较函数将该元素放到相应节点上,在定义容器时,如果没有指定比较函数,那么采用默认的比较函数,及按照键值由小到大的顺序插入元素,很多情况下,需要自己编写比较函数,


map和set内部的数据结构都是红黑树,所以比较函数是一致的,编写方法有两种:

(1)如果元素不是结构体,那么可以编写比较函数,下面程序编写的比较规则是按照键值由大到小顺序插入map:

#include<iostream>
#include<map>
using namespace std;

struct myComp{
	bool operator() (const int &a,const int &b){
		if(a!=b) return a>b;
		else return a>b;
	}
};

int main(){
	map<int,char,myComp> m;
	m[12] = 'm';
	m[1] = 'd';
	m[21] = 'f';
	m[32] = 'a';
	map<int,char,myComp>::iterator it;
	for(it = m.begin();it!=m.end();it++){
		cout<<(*it).first<<":"<<(*it).second<<endl;
	}
	return 0;
}


(2)如果元素是结构体,那么可以使用上面的方法自定义函数,也可以直接把比较函数写在结构体内:

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

struct Info{
	string name;
	float score;
	Info(string a,float b):name(a),score(b){}

	bool operator < (const Info &a) const {		//结构体内比较
		return a.score<score;
	}
};

struct myComp{			//自定义比较
	bool operator() (const Info &a,const Info &b){
		if(a.score!=b.score) return a.score>b.score;
		else return a.score>b.score;
	}
};



int main(){
	Info a("a",99),b("b",98),c("c",65),d("d",78);
	set<Info> s;
	s.insert(a);
	s.insert(b);
	s.insert(c);
	s.insert(d);
	set<Info>::iterator it;
	for(it = s.begin();it!=s.end();it++){
		cout<<(*it).name <<":"<<(*it).score<<endl;
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值