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

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

int main(){
	map 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 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 left, pair 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++ 匿名函数 

你可能感兴趣的:(#,C++/map(字典,哈希表),c++,算法,开发语言)