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

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

Linda Hamilton
Release: 2024-12-03 11:03:13
Original
943 people have browsed it

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

To:

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

The doSort method should then invoke the comparison function using the syntax:

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

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

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!

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