[英]How to sort Struct using qsort in C programming
我創建了一個結構數組,我想使用qsort對它們進行排序,以便按時間順序將日期排序為字符串month,或者我應該說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);
}
您可以定義自己的比較器來對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;
}
我認為您可以從中創建自己的比較器功能。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.