题解 | #成绩排序#

成绩排序

http://www.nowcoder.com/practice/8e400fd9905747e4acc2aeed7240978b

#include<iostream>
#include<map>//最开始想把键值对存map,想法错误,因为map会自动排序key
#include<string>
#include<vector>//键值对存容器里,然后用stable_sort完成排序就可以了
#include<algorithm>
using namespace std;
using namespace __gnu_cxx;
bool cmp_val(const pair<string,int> &left,const pair<string,int> &right);
bool cmp_val2(const pair<string,int> &left,const pair<string,int> &right);
int main(){
    int n;
    cin >> n;
    vector<pair<string,int>> score;
    score.clear();//清脏数据
    int type;
    cin >> type;
    string name;
    int val;
    while(n){
        n--;
        cin >> name >> val;
        score.push_back(pair<string,int>(name,val));
    }
    if(type == 0){
        stable_sort(score.begin(),score.end(),cmp_val2);//stable_sort是归并排序(稳定的,但效率不如快排)
    }
    if(type == 1){
        stable_sort(score.begin(),score.end(),cmp_val);
    }
    for(vector<pair<string,int>> :: iterator it = score.begin(); it < score.end(); it++){
        cout << it->first << " " << it->second << endl;
    }
    return 0;
}
bool cmp_val(const pair<string,int> &left,const pair<string,int> &right){
    return left.second < right.second;
}
bool cmp_val2(const pair<string,int> &left,const pair<string,int> &right){
    return left.second > right.second;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
2025-12-19 10:45
秋招路在何方:少了啊,我身边都是350000k*18,发三体货币
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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