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
Release: 2024-12-02 18:00:21
Original
461 people have browsed it

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

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

to:

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

Then, call the sort function as follows:

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

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

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!

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