简体   繁体   English

qsort结构降序排列

[英]qsort array of structs descending order

I have a struct that looks like this 我有一个看起来像这样的结构

typedef struct id_score{
   int id;
   int score;
} pair;

An array of size 50 holds pointers to these pairs 大小为50的数组包含指向这些对的指针

pair* array[50]

My comparator function looks like this 我的比较器功能如下所示

int struct_cmp(const void *a, const void* b) {
    pair* ia = (pair*)a;
    pair* ib = (pair*)b;
    printf("ia's score: %d ib's score: %d??? \n", ia->score, ib->score);
    return ib->score - ia->score;
}

My qsort function here 我的qsort功能在这里

size_t arr_len = sizeof(array) / sizeof(pair);
qsort(array, arr_len, sizeof(pair), struct_cmp);

Now my problem is that in the struct_cmp function, my printf shows that the values that I think should be the count in each struct in the array are all interpreted as 0 , thus not sorting the array at all. 现在我的问题是,在struct_cmp函数中,我的printf显示我认为应该作为数组中每个结构的计数的值都被解释为0 ,因此根本不对数组进行排序。 Outside of the function when I print through the array, the struct's have scores that it should have. 当我在数组中打印时,在函数之外,该结构具有应具有的分数。

Any suggestions?? 有什么建议么?? thank you! 谢谢!

For one 对于一个

size_t arr_len = sizeof(array) / sizeof(pair);

The above is wrong, as your array contains pair pointers, and not pair s. 上面的说法是错误的,因为您的数组包含pair指针,而不是pair Doing it a bit more idiomatically and with less repetition would be: 更加惯用且重复更少,可以做到:

size_t arr_len = sizeof(array) / sizeof(array[0]);

Another thing to note, is that your comparison function converts to the wrong pointer type, so the behavior of your program is undefined. 还要注意的另一件事是,您的比较函数将转换为错误的指针类型,因此程序的行为是不确定的。

Remember that the callback function will receive pointers to array elements, so if the array contains pointers, it should convert the arguments to pointers to pointers: 请记住,回调函数将接收指向数组元素的指针,因此,如果数组包含指针,则应将参数转换为指向指针的指针:

int struct_cmp(const void *a, const void* b) {
    pair* const * ia = (pair* const *)a;
    pair* const * ib = (pair* const *)b;
    printf("ia's score: %d ib's score: %d??? \n", ia->score, ib->score);
    return (*ib)->score - (*ia)->score;
}

Unlike your original function, I also strove to make it const correct. 与您的原始函数不同,我也竭力使其常量正确。 The compare callback accepts by a pointer to const, so the converted pointer should be to const as well (with const being applied to the element type, which is pair* ). 比较回调由指向const的指针接受,因此转换后的指针也应为const(将const应用于元素类型pair* ,即pair* )。


As chux pointed out, as a way to avoid overflow in the subtraction, a major improvement will be to return the following instead: 正如chux所指出的,作为一种避免减法中溢出的方法,一个主要的改进将是返回以下内容:

return ((*ib)->score > (*ia)->score) - ((*ib)->score < (*ia)->score);

Which also has the nice property of always returning -1, 0 or 1 instead of arbitrary numbers. 它还具有始终返回-1、0或1而不是任意数字的好特性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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