【问题标题】:How to sort std::list of pairs by key?如何按键对 std::list 进行排序?
【发布时间】:2020-06-12 21:58:15
【问题描述】:

我想在两个单独的函数中按 keyvaluestd::list<std::pair<string, int>> 进行排序。

我收到一条错误消息:

error: reference to non-static member function must be called
    sort(test.begin(), test.end(), sortByVal);

代码

class Test 
{
    std::list<pair<std::string, int>> test;

public:
    void sortbykey()
    {
        sort(test.begin(), test.end(), sortByVal);
    }

    bool sortByVal(const std::pair<std::string, int>& a, const std::pair<std::string, int>& b)
    {
        return (a.first < b.first);
    }
};

【问题讨论】:

标签: c++ sorting c++-standard-library std-pair stdlist


【解决方案1】:

将迭代器传递为 Legacy Random AccessIterator 所需的 std::sort。但是std::listLegacy Bidirectional Iterator,这就是错误的原因。


另一方面,std::list 有一个成员函数 std::list&lt;T&gt;::sort,如果您坚持容器必须是 std::list,这将是首选方法。

由于您需要按对的first 进行排序,因此您需要将自定义比较器(或 lambda)传递给它。

你需要的意思

void sortbykey()
{
    test.sort([](const auto& lhs, const auto& rhs) { return lhs.first < rhs.first; });
}

【讨论】:

    【解决方案2】:

    迭代器必须是随机访问迭代器。 list-iterator 不是。

    【讨论】:

    • 太棒了!正如 Paul 解释的那样,比较函数必须是静态的或独立的。
    【解决方案3】:

    您可以使用std::vector,并将比较功能设为静态

    #include <algorithm>
    #include <string>
    #include <vector>
    
    class Test {
        std::vector<std::pair<std::string, int>> test;
    
      public:
        void sortbykey() {
            sort(test.begin(), test.end(), sortByVal);
        }
    
        static bool sortByVal(const std::pair<std::string, int> &a,
                              const std::pair<std::string, int> &b) {
            return (a.first < b.first);
        }
    };
    

    【讨论】:

      猜你喜欢
      • 2011-01-08
      • 2021-07-15
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 2011-06-20
      相关资源
      最近更新 更多