std::sort function with custom compare function results error: reference to non-static member function must be called

非 Y 不嫁゛ 提交于 2019-12-12 03:06:29

问题


I have trouble using the std::sort function with my custom comparison function when defined inside a class.

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

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

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

I get the following error message:

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

When I however define compare() and sortMatrix() in the file main.cpp without any class, everything works fine. I would appreciate any help and suggestions.


回答1:


To call compare you need a Field object. You could use a lambda a call it from in there if you have C++11 support:

sort(vec.begin(), vec.end(), [this] (vector<int> a, vector<int> b) {
    return compare(a, b); });

Or just move your comparison method out of the class, you don't need to access it's members anyway.




回答2:


Thank you for the comment πάντα ῥεῖ. Your hint works very well, I ended up using a class Compare and called an operator.



来源:https://stackoverflow.com/questions/37767847/stdsort-function-with-custom-compare-function-results-error-reference-to-non

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!