gpt4 book ai didi

c++ - 如何从同一个类的另一个成员函数中调用仿函数?

转载 作者:行者123 更新时间:2023-11-30 03:35:04 26 4
gpt4 key购买 nike

我已经重载了 () 运算符来为我进行比较,我想将其作为比较器发送到 std 排序函数调用的第三个参数。现在,此调用位于另一个名为 threeSum 的成员函数中。我发现发送 Solution() 有效,但 this() 无效。这个的语法规则是什么?

class Solution 
{
public:
bool operator() (int i, int j)
{
return (i < j);
}

vector<vector<int> > threeSum(vector<int> & nums)
{
sort(nums.begin(), nums.end(), this());

vector<vector<int> > ret_vec;
...
return ret_vec;
}
};

谢谢。

最佳答案

this() 不起作用的原因是因为 this 是一个指针。您需要先取消引用它。

(*this)(args);

在你的情况下,你应该这样写:

sort(nums.begin(), nums.end(), (*this));

或者,如果你想更明确:

Solution& this_val = *this;
sort(nums.begin(), nums.end(), this_val);

关于c++ - 如何从同一个类的另一个成员函数中调用仿函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540888/

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