成绩排序(HJ68)
一:解题思路
这道题目考察了稳定排序。
二:完整代码示例 (C++版和Java版)
C++代码如下:
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; struct student { string name; int score; }; bool campare_min2max(const student& s1, const student& s2) { return s1.score < s2.score; } bool campare_max2min(const student& s1, const student& s2) { return s1.score > s2.score; } int main() { int n = 0; bool min2max =true; while (cin >> n >> min2max) { vector<student> stu(n); for (int i = 0; i < n; i++) { cin >> stu[i].name >> stu[i].score; } if (min2max) stable_sort(stu.begin(), stu.end(),campare_min2max); else stable_sort(stu.begin(),stu.end(),campare_max2min); for (int i = 0; i < n; i++) cout << stu[i].name << " " << stu[i].score << endl; } return 0; }

浙公网安备 33010602011771号