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的问题)
您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()函数对结构进行排序
严格版本的比较器需要两个常量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字段.这是您处理任何多部分比较的方式.