【问题标题】:How to call a functor from another member function of the same class?如何从同一类的另一个成员函数调用仿函数?
【发布时间】:2017-01-09 04:04:53
【问题描述】:

我已经重载了 () 运算符来为我进行比较,我想将它作为比较器发送到 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;
    }
};

谢谢。

【问题讨论】:

  • 比较器应该放在哪里?
  • sort(nums.begin(), nums.end(), std::ref(*this)); 您可能需要将运算符设为const,如bool operator() (int i, int j) const {...}

标签: c++ operator-overloading functor


【解决方案1】:

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

(*this)(args);

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

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

或者,如果你想更明确:

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

【讨论】:

  • 12 调用operator() 没有意义,std::sort 必须使用2 个不同的参数调用它才能对它们进行排序。
  • 我试图给出一个更笼统的答案,但我已经更新它以更准确地匹配问题。
  • (*this)()this_val() 都不会编译。
  • 啊,它需要真正的仿函数 - 已修复。
【解决方案2】:

非静态成员函数(包括任何函子)需要包含对象的地址作为其隐式参数。您可以使用 lambda 函数来实现效果:

vector<vector<int> > threeSum(vector<int> & nums) 
{
  auto mysort = [this](int i, int j) {
    return operator()(i, j); 
  };
  sort(nums.begin(), nums.end(), mysort);
  ...
}

这里的 lambda 函数 mysort 捕获包含对象 (this) 的运行时地址,并将其用作 operator() 的隐式参数,现在可以由 std::sort 使用。

编辑:此方法不仅适用于仿函数,也适用于其他成员函数。但是,如果您只想使用函子进行排序,那么将(*this) 直接作为sort 的第三个参数提供的另一个答案可能会更有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多