代码之家  ›  专栏  ›  技术社区  ›  Zack Lee

查找std::pair的std::vector中的最小值和最大值

  •  1
  • Zack Lee  · 技术社区  · 6 年前

    我想找出向量的最小值/最大值 pair<int, std::string>

    我的代码:

    #include <iostream>
    #include <vector>
    #include <string>
    
    int main()
    {
        std::vector<std::pair<int, std::string>> pairs;
        pairs = {{6,"a"}, {4,"b"}, {5,"c"}, {8,"d"}, {7,"e"}};
    
        int min = 0, max = 0;
    
        //how to find out min/max?
    
        std::cout << "Minimum Number : " << min << '\n';
        std::cout << "Maximum Number : " << max << '\n';
    }
    

    我想要的结果是:

    Minimum Value : 4
    Maximum Value : 8
    Program ended with exit code: 0
    


    编辑时间:

    std::sort(pairs.begin(), pairs.end());
    min = pairs[0].first;
    max = pairs[pairs.size()-1].first;
    

    虽然它的工作,我想学习一个更简单,更快的解决方案比这个。

    1 回复  |  直到 6 年前
        1
  •  5
  •   Jarod42    6 年前

    你可以用 std::minmax_element :

     const auto p = std::minmax_element(pairs.begin(), pairs.end());
     auto min = p.first->first;
     auto max = p.second->first;