2014-11-22 38 views
0

排序結構的陣列我有一個結構通過2個參數

struct employee { 
    int record; 
    int ID; 
.... 
}; 

employee * arr = (employee*) malloc(501 * sizeof (employee)); 

,我需要通過這兩個參數對它進行排序(ID在第一和記錄作爲第二)。 我使用的是非標準的快速排序與

qsort (employee, records, sizeof(employee), compare); 

但我不知道,如何編輯基本的比較功能,使得它的工作原理

我samething這樣

int comparestruct(const employee *p1, const employee *p2) 
{ 
    const struct employee *elem1 = p1;  
    const struct employee *elem2 = p2; 

    if (elem1->ID < elem2->ID) 
     return -1; 
    else if (elem1->ID > elem2->ID) 
     return 1; 
    else 
     return 0; 
} 

但這ISN不工作......

請幫忙嗎?

+2

它怎麼可能工作,如果你甚至不提'record'場? (什麼是'zam'?應該是'void'。) – ooga 2014-11-22 20:10:37

+0

typecast p1和p2給員工?不知道在那裏是否存在某種繼承關係,或者zam如何與僱員關聯 – 2014-11-22 20:13:43

+0

zam表示僱員,我將其翻譯成英文並忘記了這一點.. – 2014-11-22 20:23:56

回答

0

通常的方法是這樣的:

int comparestruct(const void *a_, const void *b_) { 
    const struct employee *a = a_; 
    const struct employee *b = b_; 
    int rv = a->ID - b->ID; 
    if (rv == 0) rv = a->record - b->record; 
    return rv; 
} 

當然,這有如果減法可能會溢出個微妙的問題。如果這是一個(這取決於你的ID和記錄號的範圍。)可能出現的問題,您可能需要:

int comparestruct(const void *a_, const void *b_) { 
    const struct employee *a = a_; 
    const struct employee *b = b_; 
    if (a->ID < b->ID) return -1; 
    if (a->ID > b->ID) return 1; 
    if (a->record < b->record) return -1; 
    if (a->record > b->record) return 1; 
    return 0; 
} 

代替