Home >Backend Development >C++ >How Can I Use a Member Function as a Comparator in `std::sort`?
Member Function as Comparator in Problem Sorting
When attempting to employ the code provided, the compiler raises an error forbidding the address retrieval of unqualified or parenthesized non-static member functions to form pointers to member functions. The issue arises from the non-static definition of the doCompare member function.
To resolve this issue, it is necessary to declare doCompare as static. However, if the function requires access to data from within MyClass, the class can be transformed into a comparison functor by altering doCompare from:
doCompare( const int & i1, const int & i2 ) { // use some member variables }
To:
bool operator () ( const int & i1, const int & i2 ) { // use some member variables }
The doSort method should then invoke the comparison function using the syntax:
doSort() { std::sort(arr, arr+someSize, *this); }
Alternatively, it's possible to leverage std::mem_fun to convert the member function into a free function. However, since std::sort accepts the comparison function by value, wrapping the function within the class itself is recommended. The modified code employing this approach appears as follows:
class MyClass { struct Less { Less(const MyClass& c) : myClass(c) {} bool operator () ( const int & i1, const int & i2 ) {// use 'myClass'} MyClass& myClass; }; doSort() { std::sort(arr, arr+someSize, Less(*this)); } }
The above is the detailed content of How Can I Use a Member Function as a Comparator in `std::sort`?. For more information, please follow other related articles on the PHP Chinese website!