为了在 qsort 中按指定字段排序,我们需要编写一个比较函数。下面是一个示例代码,它包含一个结构体和两个比较函数,它们按照结构体的不同字段排序:
#include
#include
#include
typedef struct {
int id;
char name[50];
float score;
} Student;
int compare_by_id(const void *a, const void *b) {
Student *s1 = (Student *) a;
Student *s2 = (Student *) b;
if (s1->id < s2->id) return -1;
else if (s1->id > s2->id) return 1;
else return 0;
}
int compare_by_name(const void *a, const void *b) {
Student *s1 = (Student *) a;
Student *s2 = (Student *) b;
return strcmp(s1->name, s2->name);
}
int main() {
Student students[] = {
{2, "Alice", 63.2},
{1, "Bob", 71.5},
{3, "Charlie", 84.7}
};
int n = sizeof(students) / sizeof(Student);
// sort by id
qsort(students, n, sizeof(Student), compare_by_id);
for (int i = 0; i < n; i++) {
printf("%d %s %.1f\n", students[i].id, students[i].name, students[i].score);
}
printf("\n");
// sort by name
qsort(students, n, sizeof(Student), compare_by_name);
for (int i = 0; i < n; i++) {
printf("%d %s %.1f\n", students[i].id, students[i].name, students[i].score);
}
printf("\n");
return 0;
}
在上述代码中,我们定义了一个结构体 Student,其中包含三个字段:id, name 和 score。我们还定义了两
下一篇:编写比较日期并请求用户输入的函数