简体   繁体   中英

Passing compare function into qsort c++

My compare function is dependent on data members in Foo and I therefore wish to contain it in this class. All examples use global functions which works but its not what I'm looking for. I'd like each instance of Foo to have a different compare based on the current status of the object.

class Foo
{
public:
   Foo(){}

   int Compare(const void * a,const void * b)
   {
    //Comparing logic
    //This is fine
   }

   void SortStuff(void)
   {
    qsort(ObjectArray,MAXOBJECTS,sizeof(Object*), Compare);
   }    

};

As @juanchopanza mentioned in a comment, it is strongly recommended that you use std::sort over qsort in C++. The std::sort algorithm correctly calls assignment operators and is type-safe, while qsort does not. For example, if you try using qsort to sort an array of std::string s, you'll get undefined behavior.

That said, if you absolutely must use qsort this way, the problem you're running into is the "invisible this " pointer. In C++, member functions are fundamentally different than free functions because in order to call a member function, you need to provide a receiver object. In the code you've written above, you're getting an error because qsort expects a free function that can be called with two arguments, but you've given it a member function that wants two arguments, which effectively really needs three arguments - a receiver object and two pointers.

To fix this, you have a few options. One option would be to mark the function static , indicating that it is a free function scoped inside your class rather than a member function. Another option would be to use lambdas to define the comparison function, since C++ lambdas without capture lists are free functions. I'd actually recommend that second option over the first unless you need the comparison function in multiple places, since it more clearly indicates that you just need the function as a one-off.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM