结构体数组排序
时间: 2023-07-20 08:11:28 浏览: 105
可以使用C++中的STL库中的sort函数对结构体数组进行排序,具体步骤如下:
1. 定义结构体类型和结构体数组:
```C++
struct Student {
string name;
int score;
};
Student stu[5] = {{"Tom", 90}, {"Jack", 80}, {"Lily", 95}, {"Bob", 70}, {"Lucy", 85}};
```
2. 定义比较函数:
```C++
bool cmp(Student a, Student b) {
return a.score > b.score; // 按照分数从高到低排序
}
```
3. 使用sort函数进行排序:
```C++
sort(stu, stu + 5, cmp); // 对stu数组进行排序,使用cmp函数作为比较函数
```
4. 输出排序结果:
```C++
for (int i = 0; i < 5; i++) {
cout << stu[i].name << " " << stu[i].score << endl;
}
```
完整代码如下:
```C++
#include <iostream>
#include <algorithm>
using namespace std;
struct Student {
string name;
int score;
};
bool cmp(Student a, Student b) {
return a.score > b.score; // 按照分数从高到低排序
}
int main() {
Student stu[5] = {{"Tom", 90}, {"Jack", 80}, {"Lily", 95}, {"Bob", 70}, {"Lucy", 85}};
sort(stu, stu + 5, cmp); // 对stu数组进行排序,使用cmp函数作为比较函数
for (int i = 0; i < 5; i++) {
cout << stu[i].name << " " << stu[i].score << endl;
}
return 0;
}
```
输出结果为:
```
Lily 95
Tom 90
Lucy 85
Jack 80
Bob 70
```
阅读全文
相关推荐


















