C如何给结构体排序
要给结构体排序,需要定义一个比较函数,然后使用排序算法对结构体数组进行排序。以下是一个示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student {
char name[20];
int age;
float score;
} Student;
int cmp(const void* a, const void* b) {
Student* s1 = (Student*)a;
Student* s2 = (Student*)b;
if (s1->score > s2->score) {
return -1;
} else if (s1->score < s2->score) {
return 1;
} else {
return 0;
}
}
int main() {
Student students[] = {
{"Alice", 18, 90},
{"Bob", 20, 85},
{"Charlie", 19, 95},
{"David", 18, 80},
{"Eva", 20, 87.5},
};
int n = sizeof(students) / sizeof(Student);
qsort(students, n, sizeof(Student), cmp);
for (int i = 0; i < n; i++) {
printf("%s %d %.1f\n", students[i].name, students[i].age, students[i].score);
}
return 0;
}
在这个示例中,我们定义了一个Student结构体,并且定义了一个比较函数cmp,该函数根据score字段的大小来决定排序顺序。然后我们使用qsort函数对结构体数组进行排序,并输出结果。
原文地址: https://www.cveoy.top/t/topic/8Me 著作权归作者所有。请勿转载和采集!