Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

c++ - How to pass a method to qsort?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...