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 Test::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.
Make your comparator function static. It will work.
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.
There are three ways of doing this :
Create a structure with operator() defined for the structure
struct compareFunc {
inline bool operator() (const vector<int> &a, const vector<int> &b)
{
return (a.back() < b.back());
}
};
and in sort function call in the below fashion:
std::sort(vect.begin(), vect.end(), compareFunc());
If you are using C++11 version then write your lamda function and call the comparator function defined in your class:
std::sort(vec.begin(), vec.end(), [this](vector<int> a, vector<int> b){
return (compareFun(a,b));
});
Define compareFun in your class in the below mentioned manner:
class Test { public: bool compareFun(vector a, vector b) { return (a.back() < b.back()); } };
Using static method as mentioned by one of our friend. I hope this works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With