为qsort的结构编写比较函数? [英] Writing a compare function for a structure for qsort?

查看:110
本文介绍了为qsort的结构编写比较函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用C为qsort函数编写比较函数时遇到麻烦.这是我目前拥有的:

I'm having trouble writing a compare function for qsort function in C. This is what I currently have:

int cmpfunc(const void *a, const void *b) {
    return (*(Individual*)a->fitness - *(Individual*)b->fitness);
}

我知道比较函数的工作原理,但是我不知道如何在我的名为Individual的结构中引用整数值.这是个人的结构.

I know how the compare function works but I don't understand how to reference an integer value within my structure called Individual. Here is the structure of the Individual.

typedef struct {
    PPM_IMAGE image;
    double fitness;
} Individual;

我想比较结构中的适应度值.

I want to compare the fitness values within the structure.

推荐答案

这部分

*(Individual*)a->fitness

是错误的.您尝试使用->访问fitness,但同时使用*取消引用指针.你不能两者都做!

is wrong. You try to access fitness using -> but at the same time you dereference the pointer using *. You can't do both!

这是两种解决方法.

解决方案A:使用*解引用并使用.

Solution A: Dereference using * and access fitness using .

(*(Individual*)a).fitness

解决方案B:使用->

((Individual*)a)->fitness

这两种解决方案都需要将void*转换为Individual*.

Both solutions also requires a cast from void* to Individual*.

变量b

如果您是C语言的初学者,我建议您避免在发生多种情况的情况下避免使用紧凑型语句.而是将压缩语句拆分为多个单独的语句.这将使代码更易于理解和调试.喜欢:

If you are a beginner in C I'll recommend that you avoid using compact statements where multiple things happens. Instead split the compact statement into a number of individual statements. That will make the code easier to understand and debug. Like:

int cmpfunc (const void * a, const void * b){
    Individual* pA = a;
    Individual* pB = b;
    double fitnessA = pA->fitness;
    double fitnessB = pB->fitness;
    return fitnessA - fitnessB;
}

您无需担心性能.编译器将优化代码,使其效率与单语句代码一样高效.

You don't need to worry about performance. The compiler will optimize the code to be just as efficient as the single statement code.

那是-由@chqrlie发现-请注意比较代码是错误的!

That said - as spotted by @chqrlie - notice that the compare code is wrong!

该函数返回一个整数,但fitnessA - fitnessB是将被转换为整数的双精度型.因此0.1 - 0.0最终将返回0-这不是您想要的.

The function returns an integer but fitnessA - fitnessB is a double that will be converted to an integer. So 0.1 - 0.0 will end up returning 0 - which is not what you want.

您可以在@chqrlie上看到此答案 https://stackoverflow.com/a/53466034/4386427 详细信息.

You can see this answer https://stackoverflow.com/a/53466034/4386427 from @chqrlie for further details.

代码也可以像这样更改:

The code can also be changed like:

int cmpfunc (const void * a, const void * b){
    Individual* pA = a;
    Individual* pB = b;
    double fitnessA = pA->fitness;
    double fitnessB = pB->fitness;
    if (fitnessA > fitnessB) return 1;
    if (fitnessA < fitnessB) return -1;
    return 0;
}

这篇关于为qsort的结构编写比较函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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