结构体排序

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

相关推荐

评论
1
1
分享

创作者周榜

更多
牛客网
牛客企业服务