题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/3f27a0a5a59643a8abf0140b9a8cf1f7
#include<iostream> #include<algorithm> #include<vector> struct Student { int num; int grade; Student(int n, int g) : num(n), grade(g) { } }; bool compare(const Student& a, const Student& b) { if(a.grade < b.grade) { return true; }else if(a.grade > b.grade) { return false; } return a.num < b.num; } int main() { int n; std::cin >> n; std::vector<Student> students; students.reserve(n);//预先指定要分配的内存数量 for(int i = 0;i < n;i++) { int p,q; std::cin >> p >> q; students.emplace_back(p, q);//直接传递参数,利用构造函数,而不是传递对象,避免复制加快执行速度 } std::sort(students.begin(), students.end(), compare); for(Student student : students) { std::cout << student.num << " " << student.grade << "\n"; } }