Sort vector of pairs: No matching function

1k Views Asked by At

I have followed the solution given here to sort a vector of pairs.

And I get

linear_problem.h:275:

error: no matching function for call to

‘sort(std::vector<std::pair<int, double> >::iterator,
std::vector<std::pair<int, double> >::iterator, <unresolved overloaded
function type>)’
     std::sort(data.begin(), data.end(), compareFunc);

The class with the code is:

class Coefficients{
private:
    std::vector<std::pair<int, double>> data;

public:
    Coefficients(){}
    bool compareFunc(const std::pair<int, double> &a, const std::pair<int, double> &b){
        return a.first > b.first;
    }

    void sort(){
        std::sort(data.begin(), data.end(), compareFunc);
    }

};

I have no idea of what can be wrong since the code is quite like the example.

2

There are 2 best solutions below

1
On BEST ANSWER

compareFunc() is a member function and requires an instance of Coefficients to be called.

You can make it a static class member function to solve that problem:

    static bool compareFunc(const std::pair<int, double> &a, const std::pair<int, double> &b){
 // ^^^^^^
        return a.first > b.first;
    }

    void sort(){
        std::sort(data.begin(), data.end(), &Coefficients::compareFunc);
                                         // ^^^^^^^^^^^^^^
    }
0
On

using c++14, the best solution is very easy to write thanks to lambdas

std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
    return left.second < right.second;
});

or you can use comparator like:

struct comp{
    bool operator()(const std::pair<int,int> &left, const std::pair<int,int> &right) {
        return left.second < right.second;
    }
};

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