我已经创建了一个struct数组,我想使用qsort对它们进行排序,以按时间顺序将日期排序到字符串月份,或者我应该说char month []。如何使以下代码显示根据一个月的结构。请指教。感谢
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);
}
答案 0 :(得分:3)
您可以定义自己的比较器来排序http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/
因此,要对整数进行排序,请使用
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;
}
我认为你可以自己制作比较器功能。
答案 1 :(得分:3)
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 */
...
}
然后
qsort(dates, total, sizeof(*dates), cmp);