2013-10-09 57 views
0

我有一系列的事件,我想根據他們的年份對它們進行排序,然後按月對每一年進行排序,然後對每個月按日進行排序,然後對每一天按小時進行排序。如何基於C中的多個字段對數組進行排序?

typedef struct { 
    struct tm start; 
    struct tm end; 
} event; 
... 
event events[100]; 

我只需要擔心排序與start日期。我一直在掙扎幾個小時...

+0

您可以通過閱讀有關標準庫函數['qsort'(http://en.cppreference.com/w/c/algorithm/啓動快速排序)。 –

+0

我已經看過它,我只是不知道如何使用一個函數作爲它需要的參數。我現在知道了 –

回答

5

您可以用同樣的方法任何在多個鍵上排序:一次一個,按您想要的優先順序排列。

一個qsort()回調可能是這個樣子:

static int event_compare(const void *a, const void *b) 
{ 
    const event *ae = a, *be = b; 

    if(ae->start.tm_year < be->start.tm_year) 
    return -1; 
    else if(ae->start.tm_year > be->start.tm_year) 
    return 1; 
    /* Years are equal, try to solve that by checking month. */ 
    if(ae->start.tm_month < be->start.tm_month) 
    return -1; 
    else if(ae->start.tm_month > be->start.tm_month) 
    return 1; 
    /* Months are equal, go on with day, and so on. */ 
} 
+0

我不知道如何使用'qsort'。非常感謝! –

相關問題