题解 | #成绩排序#

成绩排序

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

  • 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;
    }
}
全部评论

相关推荐

程序员小白条:你不是有一段实习了吗,现在找中大厂实习?过段时间要秋招了
我的简历长这样
点赞 评论 收藏
分享
但听说转正率很低,我现在有在实习了,好纠结要不要去
熬夜脱发码农:转正率低归低,但是实习的经历你可以拿着,又不是说秋招不准备了
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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