• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

C++-map获取mapvalue最大值、最小值对应的键值对

武飞扬头像
u013250861
帮助1

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

简述:通过调用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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgekfge
系列文章
更多 icon
同类精品
更多 icon
继续加载