如何将方法传递给qsort? [英] How to pass a method to qsort?

查看:63
本文介绍了如何将方法传递给qsort?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个包含一些数据的类,它在某个时间点对它们进行排序。我使用 qsort(),并且希望将比较函数作为方法保留在类中。问题是如何将方法传递给 qsort(),以使编译器(g ++)不会发出任何警告?

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?

尝试1:

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

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

这种方式会产生错误:

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*))’

尝试2:

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

这种方式会生成警告:

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

然后如何正确执行操作?

How to do it the right way then?

推荐答案

您以& Data :: compare_records 的形式传递函数,但应以<$ c $的形式传递c> Data :: compare_records 并使其变为 static

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

这篇关于如何将方法传递给qsort?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆