问题
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