对向量排序:无匹配函数

Sort vector of pairs: No matching function

我已经按照给定的解决方案 here 对向量对进行排序。

然后我得到

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

带代码的class是:

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

};

我不知道哪里出了问题,因为代码与示例非常相似。

compareFunc() 是成员函数,需要调用 Coefficients 的实例。

你可以使它成为一个 static class 成员函数来解决这个问题:

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

使用 c++14,由于 lambdas

,最好的解决方案很容易编写
std::sort(v.begin(), v.end(), [](auto &left, auto &right) {
    return left.second < right.second;
});

或者您可以像这样使用比较器:

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