Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a method to qsort?

Tags:

c++

There is a class that contains some data and it sorts them at some point of time. I use qsort() and I'd like to keep the comparing function within the class as a method. The question is how to pass a method to qsort() so that the compiler (g++) don't throw any warnings?

Attempt 1:

int Data::compare_records(void * rec_1, void * rec_2){
  // [...]
}

void Data::sort(){
  qsort(records, count, sizeof(*records), &Data::compare_records);
}

This way generates an error:

error: cannot convert ‘int (Data::*)(const void*, const void*)’ to ‘int (*)(const void*, const void*)’ for argument ‘4’ to ‘void qsort(void*, size_t, size_t, int (*)(const void*, const void*))’

Attempt 2 :

void Data::sort(){
  qsort(
    records, count, sizeof(*records),
    (int (*)(const void*, const void*)) &Data::compare_records
  );
}

This way generates a warning:

warning: converting from ‘int (Data::*)(const void*, const void*)’ to ‘int (*)(const void*, const void*)’

How to do it the right way then?

like image 894
Kalmar Avatar asked Oct 02 '12 11:10

Kalmar


3 Answers

If you must use qsort and not std::sort (recommended), declaring the member method as static should be enough.

like image 71
Luchian Grigore Avatar answered Oct 24 '22 03:10

Luchian Grigore


You pass the function as &Data::compare_records, but you should pass it as Data::compare_records and also make it static

like image 21
Anton Guryanov Avatar answered Oct 24 '22 04:10

Anton Guryanov


Don't use qsort in C++. Use std::sort and boost/std::bind. Member function-pointer cannot been converted to function-pointer. Your method should be static, or it should be free function.

see Is the type of “pointer-to-member-function” different from “pointer-to-function”? for an explanation.

like image 38
ForEveR Avatar answered Oct 24 '22 04:10

ForEveR