• stable_sort (first, last) 和 sort() 函数功能相似,不同之处在于,对于 [first, last) 范围内值相同的元素,该函数不会改变它们的相对位置。

  • key value除了map,还可以通过pair方式用vector来存

  • lamda函数排序

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int n, flag;
    while(cin >> n) {
        vector<pair<string, int>> grades(n);
        cin >> flag;
        string name; 
        int grade;
        for(int i = 0; i < n; i++) {
            cin >> name >> grade;
            grades[i] = make_pair(name, grade);
        }
        
        if(flag) { //从小到大
            stable_sort(grades.begin(), grades.end(), [](const pair<string, int>& a, const pair<string, int>& b) {
                return a.second < b.second;
            });
        }else {
            stable_sort(grades.begin(), grades.end(), [](const pair<string, int>& a, const pair<string, int>& b) {
                return a.second > b.second;
            });
        }
        
        for(int i = 0; i < n; i++) {
            cout << grades[i].first << " " << grades[i].second << endl;
        }
        return 0;
    }
}