Search code examples
c++operator-overloadingfunctor

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.


Solution

  • 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);