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
Release: 2024-12-08 22:17:14
Original
880 people have browsed it

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

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

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

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!

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