[英]How to sort Struct using qsort in C programming
I have created an array of struct and i would like to sort them using qsort to sort dates chronologically to the string month or i should say char month[]. 我创建了一个结构数组,我想使用qsort对它们进行排序,以便按时间顺序将日期排序为字符串month,或者我应该说char month []。 how can i make the following code display the struct according to a month. 我如何使以下代码根据一个月显示该结构。 please advice. 请指教。 thanks 谢谢
struct dates
{
int index;
int day;
int year;
char month[15];
};
int i=0;
int count = 0 ;
char test ='\0';
int total =0;
printf("Please enter the number of dates you need to display");
scanf("%d",&total);
struct dates *ip[total];
for(count =0; count< total; count++){
ip[count] = (struct dates*)malloc(sizeof(struct dates));
printf("\nEnter the name month.");
scanf("%s", ip[count]->month);
printf("\nEnter the Day.");
scanf("%d",&ip[count]->day);
printf("\nEnter the Year.");
scanf("%d", &ip[count]->year);
}
for(i=0; i<total; i++){
printf("%s %d %d\n\n",ip[i]->month,ip[i]->day,ip[i]->year);
}
you can define your own comparator to sort http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ 您可以定义自己的比较器来对http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/进行排序
So to sort integers you would use 所以要对整数进行排序
int intcomp(void *a, void *b){
int *_a = (int *)a;
int *_b = (int *)b;
if(*_a > *_b) return -1;
if(*_a == *_b) return 0;
return 1;
}
I think you can make your own comparator function from that. 我认为您可以从中创建自己的比较器功能。
There's an example in the man page of qsort
qsort
的手册页中有一个示例
static int
cmp(const void *p1, const void *p2)
{
int y1 = ((const struct dates*)p1)->year;
int y2 = ((const struct dates*)p2)->year;
if (y1 < y2)
return -1;
else if (y1 > y2)
return 1;
/* years must be equal, check months */
...
}
and then 接着
qsort(dates, total, sizeof(*dates), cmp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.