Search code examples
c++sortingstdstd-pairstdlist

How to sort std::list of pairs by key?


I would like to sort a std::list<std::pair<string, int>> by the key as well as by the value in two separate functions.

I am getting an error that says:

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

The code

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);
    }
};


Solution

  • The std::sort required to have the iterator passed to be Legacy Random AccessIterator. But the std::list has Legacy Bidirectional Iterator, which is why the error.


    On the other hand, the std::list has a member function std::list<T>::sort, which would be prefered way to go, if you insist the container must be std::list.

    Since you need to sort by the first of the pairs, you need to pass a custom comparator (or lambda) to it.

    Meaning you need

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