Home >Backend Development >C++ >How Can I Use a Member Function as a Comparator in C `std::sort`?

How Can I Use a Member Function as a Comparator in C `std::sort`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-02 18:00:21452browse

How Can I Use a Member Function as a Comparator in C   `std::sort`?

Implementing Member Function Comparators for Sorting

In C , sorting a collection requires a comparator function. Attempting to utilize a member function as a comparator may result in a compilation error.

Problem

Consider the following class:

class MyClass {
    int * arr;
    // ...

    doCompare( const int & i1, const int & i2 ) { // uses member variables } 

    doSort() { std::sort(arr,arr+someSize, &doCompare); }
};

Compiling this code may generate an error:

ISO C forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.

Solution

To resolve this issue, one approach is to make doCompare a static member function. However, if doCompare requires access to MyClass data, you can convert MyClass into a comparison functor.

This can be achieved by changing:

doCompare( const int & i1, const int & i2 ) { // use some member variables }

to:

bool operator () ( const int & i1, const int & i2 ) { // use member variables }

Then, call the sort function as follows:

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

Additionally, the doSort method should return a value, such as void.

Another option is to wrap the member function within the class, as demonstrated in the following example:

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 C `std::sort`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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