结构体按姓名排序
时间: 2023-07-01 21:04:59 浏览: 44
假设我们有一个结构体定义如下:
```c
struct Person {
char name[50];
int age;
};
```
可以使用 `qsort` 函数来对结构体数组进行排序。我们需要自己定义一个比较函数,用来告诉 `qsort` 如何比较两个结构体的大小关系。比较函数的定义如下:
```c
int compare(const void *a, const void *b) {
const struct Person *p1 = a;
const struct Person *p2 = b;
return strcmp(p1->name, p2->name);
}
```
在比较函数中,我们首先将 `a` 和 `b` 转换成指向 `struct Person` 类型的指针,然后使用 `strcmp` 函数比较两个结构体的姓名。如果 `p1->name` 比 `p2->name` 小(即字典序更小),则返回一个负数;如果 `p1->name` 比 `p2->name` 大,则返回一个正数;如果两者相等,则返回 0。
使用 `qsort` 函数对结构体数组按姓名排序的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char name[50];
int age;
};
int compare(const void *a, const void *b) {
const struct Person *p1 = a;
const struct Person *p2 = b;
return strcmp(p1->name, p2->name);
}
int main() {
struct Person people[] = {
{"Alice", 25},
{"Bob", 30},
{"Charlie", 20},
{"David", 35},
{"Eve", 28}
};
int n = sizeof(people) / sizeof(people[0]);
qsort(people, n, sizeof(struct Person), compare);
for (int i = 0; i < n; i++) {
printf("%s %d\n", people[i].name, people[i].age);
}
return 0;
}
```
输出结果为:
```
Alice 25
Bob 30
Charlie 20
David 35
Eve 28
```