结构体排序

#include <iostream>
#include <string>
#include <algorithm>  // 用于排序
using namespace std;

// 定义学生结构体
struct Student {
    string name;       // 姓名
    int programming;   // 编程成绩
    int math;          // 数学成绩
    int english;       // 英语成绩

    // 计算总分
    int totalScore() const {
        return programming + math + english;
    }
};

// 自定义排序规则
bool compareStudents(const Student &amp;a, const Student &amp;b) {
    if (a.totalScore() != b.totalScore()) {
        return a.totalScore() > b.totalScore();  // 按总分从高到低排序
    } else {
        return a.name < b.name;  // 总分相同,按姓名字典序排序
    }
}

int main() {
    int n;
    cin >> n;  // 读取学生数量

    // 定义学生数组
    Student students[n];

    // 读取每个学生的信息
    for (int i = 0; i < n; i++) {
        cin >> students[i].name >> students[i].programming >> students[i].math >> students[i].english;
    }

    // 对学生数组进行排序
    sort(students, students + n, compareStudents);

    // 输出排序后的学生姓名和总分
    for (int i = 0; i < n; i++) {
        cout << students[i].name << &quot; &quot; << students[i].totalScore() << endl;
    }

    return 0;
}
全部评论

相关推荐

今天 16:52
已编辑
门头沟学院 Java
周五投的,流程今天结束
投递地平线等公司7个岗位
点赞 评论 收藏
分享
屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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