简体   繁体   中英

How to call a functor from another member function of the same class?

I have overloaded the () operator to do the comparison for me and I want to send that as the comparator to the third argument of the std sort function call. Now, this call is in another member function called threeSum . I found that sending it Solution() works but this() doesn't work. What are the syntax rules for 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;
    }
};

Thank you.

The reason this() doesn't work is because this is a pointer. You need to dereference it first.

(*this)(args);

In your case, you should write this:

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

Or, if you want to be more explicit:

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

A non-static member function (including any functor) requires the address of the containing object as its implicit argument. You could use a lambda function to achieve the effect:

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

Here the lambda function mysort captures the run-time address of the containing object ( this ) and use it as an implicit argument to operator() , which can now be used by std::sort .

EDIT: This method will not only work for functors but other member functions as well. But if you only want to use the functor for sorting, then the other answer which provides (*this) directly as the 3rd argument to sort might be slightly more efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM