Home > Backend Development > C++ > How Can I Correctly Use Member Functions as Comparators in C Sorting?

How Can I Correctly Use Member Functions as Comparators in C Sorting?

Barbara Streisand
Release: 2024-12-01 19:27:12
Original
809 people have browsed it

How Can I Correctly Use Member Functions as Comparators in C   Sorting?

Addressing Issues with Member Function Comparators in Sorting

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

};
Copy after login

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 }
Copy after login

Subsequently, the sorting operation can be invoked as:

doSort() { std::sort(arr, arr+someSize, *this); }
Copy after login

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)); }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template