C++问题 E: 【基础】记录排序 输入n个学生记录(每个学生记录包括学号、姓名、年龄、性别、成绩),组成记录数组,然后按成绩由高到低的次序排序,输出排序后的全部学生记录。
时间: 2024-02-07 07:02:21 浏览: 42
这是一个经典的排序问题,可以使用C++的结构体和标准库中的sort函数来实现。下面是一个示例代码:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
struct Student {
int id;
string name;
int age;
char gender;
double score;
};
// 按成绩从高到低排序的比较函数
bool cmp(Student a, Student b) {
return a.score > b.score;
}
int main() {
int n;
cin >> n;
Student* arr = new Student[n];
for (int i = 0; i < n; i++) {
cin >> arr[i].id >> arr[i].name >> arr[i].age >> arr[i].gender >> arr[i].score;
}
sort(arr, arr + n, cmp);
for (int i = 0; i < n; i++) {
cout << arr[i].id << " " << arr[i].name << " " << arr[i].age << " " << arr[i].gender << " " << arr[i].score << endl;
}
delete[] arr;
return 0;
}
```
在上面的代码中,我们定义了一个结构体`Student`,表示每个学生的记录。然后我们定义了一个按成绩从高到低排序的比较函数`cmp`,并使用标准库中的`sort`函数对学生记录数组进行排序。最后输出排序后的结果即可。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)