简体   繁体   English

比较内置qsort函数中的函数

[英]compare function in inbuilt qsort function

I am trying to use the inbuilt qsort function in C to sort a structure 我试图在C中使用内置的qsort函数来对结构进行排序

typedef struct abc{
  long long int fir;
  long long int sec;
}abc;

In the compare function I used the below code so that if the variable "fir" is same between any two elements in the array of structure abc then the sorting condition will depend on the variable "sec". 在比较函数中,我使用下面的代码,这样如果变量“fir”在结构abc数组中的任何两个元素之间相同,那么排序条件将取决于变量“sec”。

long long int cmp(const abc*  e1, const abc* e2)
{
if(e1->fir==e2->fir)
       return e1->sec-e2->sec;
else
    return e1->fir-e2->fir;
} 

The code doesn't seem to work properly. 代码似乎无法正常工作。 What is the correct method to do it? 这样做的正确方法是什么?

long long int cmp(const abc*  e1, const abc* e2)

does not have the correct signature for a qsort comparison function, so your program has undefined behavior. 没有qsort比较函数的正确签名,因此您的程序具有未定义的行为。 You should set your compiler warning flags high, and it will warn you of such things. 您应该将编译器警告标志设置为高,并且它会警告您这些事情。

Your actual test is fine as long as the subtraction can't overflow, which is probably not a problem for long long. 只要减法不能溢出,您的实际测试就可以了,这可能不会长时间存在问题。 Edit The subtraction is not fine here, precisely because the return value of cmp must be an int . 编辑这里的减法不正确,正是因为cmp的返回值必须是int The result of the subtraction long long , so if you have large values the result is too big to fit into an int and qsort is sure to produce the wrong order. 减法的结果long long ,所以如果你有大的值,结果太大qsort适合intqsort肯定会产生错误的顺序。

More generally, though, this is more accurate: 但更一般地说,这更准确:

int cmp(const void* v1, const void* v2)
{
    const struct abc* p1 = v1;
    const struct abc* p2 = v2;

    if (p1->fir < p2->fir)
        return -1;
    else if (p1->fir > p2->fir)
        return 1;
    else
        return p1->sec < p2->sec? -1 : p1->sec > p2->sec? 1 : 0;       
}

The built-in qsort you're using probably expects a "lower-than" (operator<) predicate, which is the normal terminology for C++. 你正在使用的内置qsort可能需要一个“低于”(operator <)谓词,这是C ++的常用术语。 And yours returns true in both cases as long as the arguments aren't equal. 只要参数不相等,你的两种情况都会返回true。

You have to return true IFF (if and only if) e1<e2 . 你必须返回真正的IFF(当且仅当) e1<e2

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

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