使用带有结构数组的qsort需要帮助

Jul*_*dez 9 c arrays struct qsort

现在,我已经看到了各种各样的例子,但我不明白他们的意思.

这是我的结构

typedef struct profile{
    char gender[1];
    double soc;
       . . .
} PROFILE;
Run Code Online (Sandbox Code Playgroud)

soc是社会保障号码,我将要排序.

我知道你需要一个比较功能,但我不知道如何提出我需要的确切内容.

小智 24

以下是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;
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你

卡捷琳娜迪米特里斯

(所有关于pitsi的问题)

  • 您的“compare”函数不正确:价格之间的差异可能大于“int”类型的范围。例如:“-3”和“INT_MAX”为不适合“int”类型的表达式生成“INT_MAX + 3”,调用未定义的行为,并且在大多数当前硬件上计算结果为负数,尽管比较应返回正数数字。 (2认同)

Mit*_*eat 8

Soc几乎肯定不会是类型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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢你指出了 const void *.

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


Jon*_*ler 5

严格版本的比较器需要两个常量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);
}
Run Code Online (Sandbox Code Playgroud)

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

  • @Chris:au contraire - 我的功能完全是上流社会; 先生们,女士们,你不知道吗?只要没有溢出,减法机制就可以工作; 比较机制无论如何都有效. (2认同)
  • 通过研究最近的一个问题,我对@ChrisLutz 向他的代表提出的建议感到惊讶。+1 为 JL。 (2认同)