map中key值自定义排序的常用方式

1、代码示例: 关注注释

// 模板为stl库提供 
template <class T>  
struct less {    
	bool operator() (const T& x, const T& y) const {return x<y;} 
}; 

#include <map> 
#include <utility>  
#include <iostream>   

using namespace std;  

// 自定义key值  
struct mytest {     
	int a_;  
	int b_;  
	mytest() = default;    
	mytest(int a, int b) : a_(a), b_(b) {}
}; 
// 实现key值得小于运算符
bool operator<(const mytest& mytest1, const mytest& mytest2) 
{    
	return std::tie(mytest1.a_,mytest1.b_) < std::tie(mytest2.a_,mytest2.b_); 
}   
int main() 
{
	// map中自定义排序需要实现小于判断:可以通过函数指针形式或函数对象形式  
	// 通过框架提供得std::less<>模板类完成函数对象的创建    
	std::map<mytest, int, std::less<mytest>> my;    
	my.insert(std::make_pair<mytest, int>(mytest(5,1), 3));      
	my.insert(std::make_pair<mytest, int>(mytest(1,2), 3));   
	if (my.find(mytest(5,1)) != my.end()) {      
		cout << "GET IT" << endl;   
	}    
	return 0; 
}   

注:find的实现通过A不小于B,且B不小于A来实现。

参考资料:
1、std::map::map
2、STL自定义排序函数:sort()函数;priority_queue,set,map等容器排序函数

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值