zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

C++Map 获取 value 对应 最大值 键值 最小值
2023-09-27 14:20:39 时间
//定义比较的函数
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++ 匿名函数