gpt4 book ai didi

c++ - 如何在类中声明自定义比较函数?

转载 作者:太空宇宙 更新时间:2023-11-04 14:59:28 26 4
gpt4 key购买 nike

当我在类中定义自定义比较函数时,我会得到错误:

'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();
}
);

关于c++ - 如何在类中声明自定义比较函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57711514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com