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

墨蓝 2023-09-25 14:18 198阅读 0赞
  1. //定义比较的函数
  2. bool cmp_value(const pair<int, int> left,const pair<int,int> right){
  3. return left.second < right.second;
  4. }
  5. int main(){
  6. map<int, int> test;
  7. //初始化
  8. test.emplace(10, 5);
  9. test.emplace(3, 17);
  10. test.emplace(19, 20);
  11. test.emplace(20, 15);
  12. //输出按序排列的key值
  13. for (auto it : test)
  14. cout << it.first << " ";
  15. cout << endl;
  16. //i是迭代器 返回值为19-20
  17. auto i= max_element(test.begin(),test.end(),cmp_value);
  18. cout << i->first << i->second << endl;
  19. }

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

使用匿名函数重构:

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

打印结果:

  1. 3 10 19 20
  2. 19,20

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

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

发表评论

表情:
评论列表 (有 0 条评论,198人围观)

还没有评论,来说两句吧...

相关阅读