Reputation: 919
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.
Upvotes: 1
Views: 578
Reputation: 470
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.
Upvotes: 1
Reputation: 6031
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);
Upvotes: 1