jun
jun

Reputation: 143

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

Upvotes: 2

Views: 808

Answers (3)

JeJo
JeJo

Reputation: 32852

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

Upvotes: 3

Ayman Al-Qadhi
Ayman Al-Qadhi

Reputation: 129

You can use std::vector, and make the comparison function static

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

Upvotes: 2

Roland Schulz
Roland Schulz

Reputation: 417

The iterator has to be a random access iterator. A list-iterator isn't.

Upvotes: 2

Related Questions