题解 | #成绩排序#
成绩排序
https://www.nowcoder.com/practice/0383714a1bb749499050d2e0610418b1
#include<vector> #include<string> #include<iostream> #include<tuple> #include<algorithm> using namespace std; bool compare1(tuple<string,int> x, tuple<string, int> y) { return get<1>(x) > get<1>(y); } bool compare2(tuple<string, int> x, tuple<string, int> y) { return get<1>(x) < get<1>(y); } int main() { int n,mode; vector < tuple<string, int> > vec; while (cin >> n>> mode) { vec.clear(); while (n--) { string a; int b; cin >> a >> b; vec.emplace_back(tuple<string, int>(a, b)); } if (mode == 0) stable_sort(vec.begin(), vec.end(), compare1); else { stable_sort(vec.begin(), vec.end(), compare2); } for (auto it = vec.begin(); it != vec.end(); it++) { cout << get<0>(*it) << " " << get<1>(*it) << endl; } } }
这题的关键在于:
- 使用tuple
- 使sort变成稳定的->stable_sort,或者增加一个计数参数