C++ 排序算法:按成绩和学号排序输出学生信息
C++ 代码:按成绩和学号排序输出学生信息
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Student {
int id; // 学号
int score; // 成绩
};
bool compareStudent(const Student& a, const Student& b) {
if (a.score != b.score) {
return a.score > b.score; // 成绩降序
} else {
return a.id < b.id; // 学号升序
}
}
int main() {
int n; // 学生人数
cin >> n;
vector<Student> students(n);
for (int i = 0; i < n; ++i) {
cin >> students[i].id >> students[i].score;
}
sort(students.begin(), students.end(), compareStudent);
for (int i = 0; i < n; ++i) {
if (students[i].score > 60) {
cout << students[i].id << ' ' << students[i].score << endl;
}
}
return 0;
}
代码解释:
- 结构体
Student: 定义一个结构体,用于存储每个学生的学号id和成绩score。 - 比较函数
compareStudent: 定义一个比较函数,用于按照成绩降序,成绩相同时学号升序进行排序。 - 主函数
main:- 输入学生人数
n。 - 使用
vector存储所有学生信息。 - 使用
sort函数对students向量进行排序,传入比较函数compareStudent。 - 遍历排序后的
students向量,输出成绩大于 60 的学生信息。
- 输入学生人数
使用方法:
- 将代码保存为
.cpp文件。 - 使用 C++ 编译器编译代码,例如
g++。 - 运行可执行文件,输入学生人数和每个学生的学号及成绩,即可得到按要求排序输出的结果。
示例:
输入:
5
12345678901 70
12345678902 90
12345678903 65
12345678904 50
12345678905 80
输出:
12345678902 90
12345678905 80
12345678901 70
12345678903 65
原文地址: https://www.cveoy.top/t/topic/oQOX 著作权归作者所有。请勿转载和采集!