[英]Sorting an struct array in C with qsort function
首先,我看到了一些示例,例如:
但是他們對我不起作用。
我的結構是
typedef struct Team {
int total;
char name[N][N]; // Nombre
int points[N]; // Points
int pg[N]; // Won Matches
int pe[N]; // Tied Matches
int pp[N]; // Lost Matches
int gf[N]; // Goals For
int gc[N]; // Goals Against
} Teams;
int compareTeams(struct Team *e1, struct Team *e2){
int comparer;
int dg1 = e1->gf - e1->gc;
int dg2 = e2->gf - e2->gc;
//classified according to the points
if (e1->points > e2->points) {
comparer=-1;
} else if (e1->points < e2->points) {
comparer=1;
} else {
// with the same points, goal difference check
if (dg1 > dg2) {
comparer=-1;
} else if (dg1 < dg2) {
comparer=1;
} else {
// with the same goal difference , we check who scored more goals
if(e1->gf > e2->gf) {
comparer=-1;
} else if (e1->gf < e2->gf) {
comparer=1;
} else
comparer=0;
}
}
return comparer;
}
在主要功能中,我有這個:
Teams teams[100];
qsort(teams, teams->total, sizeof(struct Team), &compareTeams);
但顯然,它不起作用:(
您只有一個結構:
typedef struct Team {
int total;
char name[N][N]; // Nombre
int points[N]; // Points
int pg[N]; // Won Matches
int pe[N]; // Tied Matches
int pp[N]; // Lost Matches
int gf[N]; // Goals For
int gc[N]; // Goals Against
} Teams;
該結構的名稱不正確; 它不是團隊,而是聯盟。 除total
以外的所有字段本身都是數組。 如果要對該結構進行排序,則必須同時交換所有數組,因為它們本質上是獨立的。 qsort
無法做到這一點; 您將必須編寫自己的排序算法。
當您重組數據時,它使團隊的管理和排序更加容易:團隊應只包含自身的數據:
typedef struct Team {
char name[24];
int points; // Points
int won, drawn, lost; // Match records
int scored, conceded; // Goal records
} Teams;
然后,您可以創建一組團隊:
Team league[] = {
{"FC Bayern Muenchen", 85, 27, 4, 2, 77, 16},
{"Borussia Dortmubd", 77, 24, 5, 4, 80, 32},
{"Bayer 04 Leverkusen", 57, 17, 6, 10, 53, 38},
{"Borussia M'Gladbach", 52, 16, 4, 13, 65, 50},
// ...
};
然后編寫一個比較函數來遵循qsort
使用的定義:
int compareTeams(const void *p1, const void *p2)
{
const Team *e1 = p1;
const Team *e2 = p2;
int dg1 = e1->gf - e1->gc;
int dg2 = e2->gf - e2->gc;
if (e1->points > e2->points) return -1;
if (e1->points < e2->points) return 1;
if (dg1 > dg2) return -1;
if (dg1 < dg2) return 1;
if (e1->gf > e2->gf) return -1;
if (e1->gf < e2->gf) return 1;
return 0;
}
並使用它:
qsort(league,
sizeof(league) / sizeof(*league), // number of teams
sizeof(*league), // size of one team
compareTeams);
重組意味着將每個團隊的數據保存在同一結構中,而不是交換許多獨立的數組以保持同步,而是交換整個團隊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.