题解 | #成绩排序#

成绩排序

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

#include <iostream>
#include<algorithm>
#include <random>
#include<vector>
#include<string>
using namespace std;
using student = struct {
    string name;
    int score;
    int order;
};
int flag;

bool compare(const student& student1, const student& student2) {
    if (student1.score != student2.score) {
        if (flag == 0)
            return student1.score > student2.score;
        if (flag == 1)
            return student1.score < student2.score;
    } else if(student1.score == student2.score) {
            return student1.order < student2.order;
    }
    return false;
}

int main() {
    int n;
    cin >> n;
    cin >> flag;
    vector<student> students;
    for (int i = 0; i < n; i++) {
        student a;
        string aname;
        int ascore;
        int aorder;
        cin >> aname;
        cin >> ascore;
        aorder=i;
        a.name = aname;
        a.score = ascore;
        a.order=aorder;
        students.push_back(a);
    }

    sort(students.begin(), students.end(), compare);

    for (int i = 0; i < students.size(); i++) {
        cout << students[i].name << ' ' << students[i].score << endl;
    }
    return 0;
}

使用c++ 的sort函数,可以很方便的解决问题

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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