我正在尝试使用qsort对结构数组进行排序。但是我在理解如何进行比较功能方面遇到了问题。我有以下结构:
typedef struct {
char name[TEAM_SIZE];
int points;
} TEAM;
而且我试图在每个团队获得最高分之后对其进行排序。
qsort(team, NUMBER_OF_TEAMS, sizeof(team), compare_points);
比较功能:
int compare_points(const void *a, const void *b) {
TEAM *p1 = (TEAM *)a;
TEAM *p2 = (TEAM *)b;
if(p1->points < p2->points) {
return 1;
}
else {
return -1;
}
}
你会怎么做?
输出:
Before:FCN 38
Before:FCM 59
Before:OB 46
Before:AGF 37
Before:AAB 50
Before:FCK 71
Before:HOB 18
Before:SDR 62
Before:RFC 47
Before:BIF 54
Before:EFB 30
Before:VFF 40
After:FCM 59
After 8
After:OB 46
After:AGF 37
After:AAB 50
After:FCK 71
After:HOB 18
After:SDR 62
After:RFC 47
After:BIF 54
After:EFB 30
After:VFF 40
答案 0 :(得分:4)
您的qsort()
来电错误:
qsort(team, NUMBER_OF_TEAMS, sizeof(team), compare_points);
第三个参数必须是数组的每个元素的大小。您正在传递整个数组的大小或指针的大小,具体取决于team
的声明方式。你想要:
qsort(team, NUMBER_OF_TEAMS, sizeof(TEAM), compare_points);
此外,您的比较函数存在轻微缺陷,因为它在p1->points == p2->points
时返回-1。因为你似乎在points
成员上进行排序,当两个团队拥有相同的点数时,你的比较函数应该返回0。
示例强>
#include <stdio.h>
#include <stdlib.h>
#define TEAM_SIZE 10
typedef struct {
char name[TEAM_SIZE];
int points;
} TEAM;
int compare_points(const void *a, const void *b)
{
const TEAM *p1 = a;
const TEAM *p2 = b;
return p2->points < p1->points ? -1 : p1->points < p2->points;
}
int main()
{
TEAM teams[] =
{
{ "OB", 46 }, { "AGF", 37 },
{ "AAB", 50 }, { "FCK", 71 },
{ "HOB", 18 }, { "SDR", 62 },
{ "RFC", 47 }, { "BIF", 54 },
{ "EFB", 30 }, { "VFF", 40 }
};
size_t NUM_TEAMS = sizeof teams / sizeof *teams;
qsort(teams, NUM_TEAMS, sizeof(TEAM), compare_points);
for (size_t i=0; i< NUM_TEAMS; ++i)
printf("%s : %d\n", teams[i].name, teams[i].points);
return 0;
}
<强>输出强>
FCK : 71
SDR : 62
BIF : 54
AAB : 50
RFC : 47
OB : 46
VFF : 40
AGF : 37
EFB : 30
HOB : 18