C语言 需要帮助将 qsort 与结构数组一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6105513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:44:23  来源:igfitidea点击:

Need help using qsort with an array of structs

carraysstructqsort

提问by Julian Hernandez

Now, I have seen various examples, but I don't get what they mean.

现在,我看到了各种例子,但我不明白它们的意思。

Here's my structure

这是我的结构

typedef struct profile{
    char gender[1];
    double soc;
       . . .
} PROFILE;

where soc is social security number that I'm going to be sorting by.

其中 soc 是我将要排序的社会安全号码。

I know you need a compare function, but I don't know how to come up with the exact thing I need.

我知道你需要一个比较功能,但我不知道如何想出我需要的确切东西。

回答by koko.auth

Here is an example of using qsortfor an array of structs in C

这是qsort在 C 中用于结构数组的示例

/* qsort example */
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int price;
    int id;
} order;
order list[6];
int i = 0;

int compare (const void * a, const void * b)
{

  order *orderA = (order *)a;
  order *orderB = (order *)b;

  return ( orderB->price - orderA->price );
}

int main ()
{
    srand ( time(NULL) );

    printf("Before sorting\n");
    for(i=0; i<6; i++){ 
        list[i].price = rand()%10;
        list[i].id = i; 
        printf ("Order id = %d Price = %d \n",list[i].id, list[i].price);           
    }
    printf("AFTER sorting\n");
    int n;
    qsort (list, 6, sizeof(order), compare);
    for (n=0; n<6; n++)
         printf ("Order id = %d Price = %d \n",list[n].id, list[n].price);          
    return 0;
}

hope it helps

希望能帮助到你

katerina dimitris

卡特琳娜·迪米特里斯

(all regards to pitsi)

(所有关于pitsi)

回答by Mitch Wheat

Your Socshould almost certainly not be of type double, but anyway here's an example of what a compare function needs to return:

Soc应该几乎肯定不是 type double,但无论如何这里有一个比较函数需要返回的例子:

int compare(const void *p1, const void *p2)
{
    const struct profile *elem1 = p1;    
    const struct profile *elem2 = p2;

   if (elem1->soc < elem2->soc)
      return -1;
   else if (elem1->soc > elem2->soc)
      return 1;
   else
      return 0;
}

Thanks for pointing out the const void *.

感谢您指出 const void *.

Here is a complete example (archived): Sorting Structures with the C qsort() Function

这是一个完整的示例(已存档):使用 C qsort() 函数对结构进行排序

回答by Jonathan Leffler

The strict version of a comparator takes two constant void pointers:

比较器的严格版本采用两个常量 void 指针:

int compare(const void *v1, const void *v2)
{
    const struct profile *p1 = v1;
    const struct profile *p2 = v2;
    if (p1->gender > p2->gender)
        return(+1);
    else if (p1->gender < p2->gender)
        return(-1);
    else if (p1->soc > p2->soc)
        return(+1);
    else if (p1->soc < p2->soc)
        return(-1);
    else
        return(0);
}

This compares the gender field first, then the soc field. This is how you handle any multipart comparison.

这首先比较性别字段,然后是 soc 字段。这就是您处理任何多部分比较的方式。

回答by chqrlie

To sort the array, use qsort()and pass a comparison function.

要对数组进行排序,请使用qsort()并传递比较函数。

Here is one that produces the correct result for all possible values of the pricemember:

这是为price成员的所有可能值生成正确结果的方法:

typedef struct profile {
    char gender[1];
    double soc;
    int price;
    ...
} PROFILE;

int compare_price(const void *a, const void *b) {
    const PROFILE *oa = a;
    const PROFILE *ob = b;

    return (oa->price > ob->price) - (oa->price < ob->price);
}

int compare_soc(const void *a, const void *b) {
    const PROFILE *oa = a;
    const PROFILE *ob = b;

    return (oa->soc > ob->soc) - (oa->soc < ob->soc);
}

Notes:

笔记:

  • the simple subtraction of values produces incorrect results if the difference does not fit in the inttype. For example -2and INT_MAXcannot be correctly compared with the subtraction method. It would not work for floating point values either.

  • the above method can be used for all comparable types, including doubleexcept for NaN.

  • 如果差值不适合int类型,那么简单的值相减会产生错误的结果。例如-2INT_MAX不能与减法正确比较。它也不适用于浮点值。

  • 上述方法可用于所有可比较的类型,包括double除了NaN.

If you wish to handle NaN, here is how to group them at the end:

如果你想处理NaN,这里是最后如何将它们分组:

#include <math.h>

int compare_soc_nan_at_the_end(const void *a, const void *b) {
    const PROFILE *oa = a;
    const PROFILE *ob = b;

    if (isnan(oa->soc)) {
        return isnan(ob->soc) ? 0 : 1;
    } else
    if (isnan(ob->soc)) {
        return -1;
    } else {
        return (oa->soc > ob->soc) - (oa->soc < ob->soc);
    }
}