Static Comparator function for sort (Reasons as to why?) C++

I recently saw a couple of questions in LeetCode where I had to sort a structure or a 2D- vector using std::sort() function. Basically using a "Comparator" function for the third parameter. Since almost every solution to a problem in LeetCode is a member function of a class Solution, some C++ library functions have to be used in slightly differerent manner.

So for those who're getting a 'RunTime Error' while executing a solution having std::sort with a comparator function and are in a hurry , just add the static keyword before your comparator function,making it a static member function, and you're good to go.

And now for those who're not in a hurry and wanna know how making your comparator function static affects things, keep reading.

Allright so whenever you call a non-static member function of class outside of a class you do something like this,
obj a;
a.compare(b); //2 parameters are required - a & b
i.e. for non-static member functions, we have to provide an extra parameter for the implicit this.

Whereas making a member function static allows this call,
Solution:: compare(b); //Just 1 parameter required

Similarly, since the code for sort will be executed outside your class, we've to declare it static else the first parameter in your comparator function will be used as the implicit first parameter for this in non-static member functions.

Insights:

  • You can't make the function static if your function parameters include a reference variable.
    To make things easier, it is advisable to use lambda expressions for custom sort functions.
    [] (const auto &l, const auto &r) {return l < r;}

Thanks to @Gh05t for the insights.
Hope this clears it up :")

References:

  1. https://stackoverflow.com/questions/26131112/why-stdsort-requires-static-compare-function
Comments (6)