#include <iostream> using namespace std; #include <list> #include <string> // 降序 bool sortD(pair<string, int> s1, pair<string, int> s2) { return s1.second > s2.second; } // 升序 bool sortU(pair<string, int> s1, pair<string, int> s2) { return s1.second < s2.second; } int main() { int num, type; cin >> num >> type; list<pair<string, int>> stus; for (int i = 0; i < num; i++) { string name; int grade; cin >> name >> grade; stus.push_back(pair<string, int>(name, grade)); } if (type == 0) { stus.sort(sortD); } else if (type == 1) { stus.sort(sortU); } for(auto & s: stus){ cout << s.first << " " << s.second << endl; } }
C++的好处。list自带的排序功能拥有自定义排序方法的功能
要自己实现的话,写一个pair的冒泡排序也行