c++ - 具有自定义比较函数结果错误的 std::sort 函数:必须调用对非静态成员函数的引用

标签 c++ sorting reference non-static

当在类中定义时,我无法将 std::sort 函数与我的自定义比较函数一起使用。

class Test {
    private:
        vector< vector<int> > mat;
        bool compare(vector<int>, vector<int>);
    public:
        void sortMatrix();
}

bool Test::compare( vector<int> a, vector<int> b) {
    return (a.back() < b.back());
}

void Test::sortMatrix() {
    sort(vec.begin(), vec.end(), compare);
}

我收到以下错误消息:

error: reference to non-static member function must be called
        sort(vec.begin(), vec.end(), compare);
                                     ^~~~~~~

然而,当我在文件 main.cpp 中定义 compare()sortMatrix() 时没有任何类,一切正常。我将不胜感激任何帮助和建议。

最佳答案

Make your comparator function static. It will work.

关于c++ - 具有自定义比较函数结果错误的 std::sort 函数:必须调用对非静态成员函数的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37767847/

相关文章:

c++ - C++中复制构造函数的困惑

Excel 索引与偏移/间接 - 我不明白为什么在这种情况下偏移/间接更快

c++ - 无法删除堆内存上的指针

c++ - 如何创建一个队列,其中包含 boost::packaged_task<> 以及返回任意类型的函数?

c++ - 将xsd转换为C++代码的工具

JavaScript。如果数组包含重复数字,则 Array .sort() 方法为 Chrome 和 Firefox 返回不同的结果

c++ - c++模板的部分特化

mysql 使用维度和引号对字符串进行排序

java - 使用方法引用时参数不匹配

c++ - 理解递归中的引用参数