2012-03-22 103 views
0

我已經創建了一個結構數組,並且我想使用qsort對它們進行排序以按字母順序排序日期到字符串月份或我應該說char月份[]。我怎麼能使下面的代碼顯示一個月的結構。請指教。感謝如何在C編程中使用qsort對結構進行排序

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); 
} 
+3

你有沒有看'人qsort'?文檔解釋了你需要做的事情,並舉​​例說明如何使用它。 – 2012-03-22 17:40:07

回答

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; 
} 

我想你可以從製作自己的比較器功能。

+0

如果它是一個字符,我想比較 – user1254916 2012-03-22 22:06:17

+0

strcmp的字符串,或者您可以使用><或== – Bram 2012-03-23 08:10:25

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); 
+0

親愛的你可以請更具體。我如何在我的代碼中使用cmp方法,然後如何使用Qsort。你可以給我舉例使用我發佈的代碼 – user1254916 2012-03-22 18:16:58

+0

什麼是* p1和* p2指向 – user1254916 2012-03-22 18:18:12

相關問題