题解 | #成绩排序#pair对+lambda自定以排序规则
成绩排序
https://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int n, p;
cin >> n >> p;
vector<pair<string, pair<int,int>>> stu(n);
for(int i = 0; i < n; i++)
{
string name;
int score;
cin >> name >> score;
stu[i] = {name, {score, i}};
}
//lambda自定以排序规则(拓展:也可以通过谓词实现)
if(p)
sort(stu.begin(), stu.end(), [&](pair<string, pair<int,int>> x, pair<string, pair<int,int>> y)
{
if(x.second.first != y.second.first) return x.second.first < y.second.first;
else return x.second.second < y.second.second; //先出现的排在前面
});
else
sort(stu.begin(), stu.end(), [&](pair<string, pair<int,int>> x, pair<string, pair<int,int>> y)
{
if(x.second.first != y.second.first) return x.second.first > y.second.first;
else return x.second.second < y.second.second; //先出现的排在前面
});
for(auto PII : stu)
cout << PII.first << " " << PII.second.first << endl;
return 0;
}