In the context of sorting using member functions as comparators, a common compilation error arises due to a prohibition in ISO C against taking the address of an unqualified or parenthesized non-static member function to form a pointer to a member function.
Consider the following code snippet:
class MyClass { int * arr; // other member variables MyClass() { arr = new int[someSize]; } doCompare( const int & i1, const int & i2 ) { // use some member variables } doSort() { std::sort(arr,arr+someSize, & doCompare); } };
The error occurs when attempting to provide the address of the member function doCompare as the third argument to std::sort. To resolve this issue, the function doCompare must be declared as static. However, this approach limits the ability of doCompare to access data members of MyClass.
To overcome this limitation, one can transform MyClass into a comparison functor by modifying doCompare as follows:
bool operator () ( const int & i1, const int & i2 ) { // use some member variables }
Subsequently, the sorting operation can be invoked as:
doSort() { std::sort(arr, arr+someSize, *this); }
Note that the doSort method lacks a return value, which can be corrected as necessary.
Alternatively, std::mem_fun can be employed to convert the member function into a free function, but the syntax can be complex. Nonetheless, it is recommended to wrap the function within the class, as illustrated below:
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 Correctly Use Member Functions as Comparators in C Sorting?. For more information, please follow other related articles on the PHP Chinese website!