Home >Backend Development >C++ >How to Correctly Use Member Functions for Sorting in C ?

How to Correctly Use Member Functions for Sorting in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-08 22:17:14872browse

How to Correctly Use Member Functions for Sorting in C  ?

Member Functions as Comparison for Sorting

When using member functions as comparison criteria for sorting, compiling errors may arise due to the restriction imposed by the ISO C standard. This standard prohibits the direct addressing of an unqualified or parenthesized non-static member function to derive a pointer to a member function. Such an error can be encountered while attempting to sort an array within a class.

To resolve this issue, one solution is to declare the comparison function doCompare as static. However, if the function relies on data from the MyClass instance, an alternative approach is to transform the class into a comparison functor. This involves modifying doCompare to implement the operator() function and invoking std::sort as follows:

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

Additionally, it's worth considering the missing return value in the doSort method. For a complete implementation, it should resemble:

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

Alternatively, one can employ std::mem_fun and binding to transform the member function into a free function. Another option is to embed the function within the class, as demonstrated in the following snippet:

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

By selecting any of these approaches, developers can successfully handle the sorting of an array within a class using a member function as the comparison criteria.

The above is the detailed content of How to Correctly Use Member Functions for Sorting in C ?. 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