当我在类中定义自定义比较函数时,我会得到错误:
'Solution::myfunction': non-standard syntax; use '&' to create a pointer to member
但是如果我在类之外定义它,它就可以工作。我如何在类中内部定义它?
class Solution {
public:
bool myfunction(const vector<int> &i, const vector<int> &j) {
return i.front() < j.front());
}
vector<vector<int>> vec;
...
sort(vec.rbegin(), vec.rend(), myfunction);
}
谢谢
非静态成员函数将隐式 this
作为第一个参数。调用成员函数的正确方法是
Solution s;
std::vector<int> x;
s.myfunction(x,x);
当你真的想要一个只接受两个 vector 作为参数的函数时。将其声明为 static
或使用自由函数(首选方式)。
PS:除非你需要在不同的范围内调用相同的比较函数,否则我建议使用 lambda:
sort(vec.begin(), vec.end(),
[](const vector<int> &i, const vector<int> &j) {
return i.front()<j.front();
}
);
我是一名优秀的程序员,十分优秀!