题解 | #成绩排序#

成绩排序

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

#include <algorithm>
#include <bits/stdc++.h>
using namespace std;

struct student {
    string name;
    int score;
    int index;
};


bool compare0(student A, student B) {
    if (A.score != B.score) {
        return A.score > B.score; // 分数高的在前面
    }
    return A.index < B.index; // 如果分数相等,则先输入的在前面
}

bool compare1(student A, student B) {
    if (A.score != B.score) {
        return A.score < B.score; // 分数低的在前面
    }
    return A.index < B.index; // 如果分数相等,则先输入的在前面
}

int main() {
    int stuNum = 0;
    int way = 0;
    
    cin >> stuNum >> way;
    vector<student> stuList(stuNum);
    for(int i = 0; i < stuNum; i++) {
        cin >> stuList[i].name;
        cin >> stuList[i].score;
        stuList[i].index = i;
    }
    
    if(!way) sort(stuList.begin(), stuList.end(), compare0);
    if(way) sort(stuList.begin(), stuList.end(), compare1);
    
    for(student stu : stuList) {
        cout << stu.name << " " << stu.score << endl;
    }
    
    return 0;
}
// 64 位输出请用 printf("%lld")

1.创建student结构体,包括姓名、分数、索引(索引为了学生分数相同时进行排序)

2.创建stu数组,输入数据

3.排序,创建相应的仿函数

4.按顺序输出

全部评论

相关推荐

明天不下雨了:兄弟你是我今天看到的最好看的简历(我说的是简历风格跟简历书写)把985 211再搞亮一点。投boss就说;您好,我华科(985)研二在读,本科211。对您的岗位很感兴趣,希望能获得一次投递机会。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务