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

如何排序向量对<float,string>而不管字符串

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

    我正在整理 std::vector<std::pair<float, std::string>> 按升序排列。

    std::sort 工作,我发现字符串影响顺序,如果浮点数有相同的值。

    我的代码:

    #include <iostream>
    #include <vector>
    #include <string>
    
    int main()
    {
        std::vector<std::pair<float, std::string>> vec;
        vec = {{1, "e"}, {1, "d"}, {1, "c"}, {1, "b"}, {1, "a"}};
        std::sort(vec.begin(), vec.end());
        for (auto i : vec)
            std::cout << i.first << ", " << i.second << '\n';
    }
    

    我得到的结果是: (值绑定时按字母顺序排列)

    1, a
    1, b
    1, c
    1, d
    1, e
    Program ended with exit code: 0
    

    我想要的结果是: (以前的元素在值绑定时优先)

    1, e
    1, d
    1, c
    1, b
    1, a
    Program ended with exit code: 0
    
    3 回复  |  直到 6 年前
        1
  •  11
  •   Yksisarvinen    6 年前

    std::pair 它是不是超载了( See the reference

    默认情况下, operator < 对于

    你应该提供你自己的谓词和用法 std::stable_sort 如果成对的第一个元素相等,则保持元素的顺序。

    std::stable_sort(vec.begin(), vec.end(),
                     [](const auto& a, const auto& b){return a.first < b.first;});
    
        2
  •  0
  •   Korni    6 年前

    你可能正在寻找 std::stable_sort

        3
  •  -1
  •   Ishpreet    6 年前

    您可以提供一个比较函数 std::sort . 就像

    std::sort(vec.begin(), vec.end(), comp);
    

    在您的情况下,比较函数可以是:

    bool comp(const std::pair<float, std::string>&a, const std::pair<float, std::string>&b){
        if(a.first == b.first) return 0;
        else return a.first < b.first;
    }
    

    Live Demo