题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
#include <algorithm> #include <bits/stdc++.h> using namespace std; struct student { string name; int score; int index; }; bool compare0(student A, student B) { if (A.score != B.score) { return A.score > B.score; // 分数高的在前面 } return A.index < B.index; // 如果分数相等,则先输入的在前面 } bool compare1(student A, student B) { if (A.score != B.score) { return A.score < B.score; // 分数低的在前面 } return A.index < B.index; // 如果分数相等,则先输入的在前面 } int main() { int stuNum = 0; int way = 0; cin >> stuNum >> way; vector<student> stuList(stuNum); for(int i = 0; i < stuNum; i++) { cin >> stuList[i].name; cin >> stuList[i].score; stuList[i].index = i; } if(!way) sort(stuList.begin(), stuList.end(), compare0); if(way) sort(stuList.begin(), stuList.end(), compare1); for(student stu : stuList) { cout << stu.name << " " << stu.score << endl; } return 0; } // 64 位输出请用 printf("%lld")
1.创建student结构体,包括姓名、分数、索引(索引为了学生分数相同时进行排序)
2.创建stu数组,输入数据
3.排序,创建相应的仿函数
4.按顺序输出