1_对结构体数组进行排序
时间: 2024-02-27 21:47:38 浏览: 23
对结构体数组进行排序可以使用标准库中的qsort函数,需要自定义比较函数来指定排序规则。比如,假设有以下结构体定义:
```
typedef struct {
int id;
char name[20];
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;
}
}
```
然后在主函数中调用qsort函数进行排序:
```
int main() {
Student students[] = {
{1, "Tom", 85.5},
{2, "Jerry", 90.0},
{3, "Alice", 80.0},
{4, "Bob", 75.5},
};
int n = sizeof(students) / sizeof(Student);
qsort(students, n, sizeof(Student), cmp);
for (int i = 0; i < n; i++) {
printf("%d %s %.1f\n", students[i].id, students[i].name, students[i].score);
}
return 0;
}
```
输出结果为:
```
2 Jerry 90.0
1 Tom 85.5
3 Alice 80.0
4 Bob 75.5
```