题解 | #成绩排序#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;
}
全部评论

相关推荐

07-18 22:55
海南大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务