C++-map:获取map中value最大值、最小值对应的键值对

//定义比较的函数
bool cmp_value(const pair<int, int> left,const pair<int,int> right){
	return left.second < right.second;
}

int main(){
	map<int, int> test;
	//初始化
	test.emplace(10, 5);
	test.emplace(3, 17);
	test.emplace(19, 20);
	test.emplace(20, 15);
	//输出按序排列的key值
	for (auto it : test)
		cout << it.first << " ";
	cout << endl;
	//i是迭代器  返回值为19-20
	auto i= max_element(test.begin(),test.end(),cmp_value);
	cout << i->first << i->second << endl;
}

简述:通过调用max_element函数,给定其特定的比较方式,将会获得在给定比较方式下得结果.上述代码中,给定的比较方式是根据value值进行比较,相当于重构了<号.将返回最大值.

使用匿名函数重构:

int main(){
	map<int, int> test;
	//初始化
	test.emplace(10, 5);
	test.emplace(3, 17);
	test.emplace(19, 20);
	test.emplace(20, 15);
	//输出按序排列的key值
	for (auto it : test)
		cout << it.first << " ";
	cout << endl;
	//i是迭代器  返回值为19-20【使用匿名函数】
	auto i= max_element(map.begin(),map.end(),[](pair<char, int> left, pair<char,int> right) { return left.second < right.second; }); 
	cout << i->first << "," << i->second << endl;
}

打印结果:

3 10 19 20 
19,20

C++获取map中value最大最小值对应的键值对_普通网友的博客-CSDN博客_c++ map求最大值

C++ 匿名函数_mayue_csdn的博客-CSDN博客_c++ 匿名函数 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值