题解 | 最厉害的学生

最厉害的学生

https://www.nowcoder.com/practice/b6e7a9ca04d8418b805b3b4b7d25b4d4

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

struct Student {
    std::string name;
    int score1, score2, score3;
    int total;

    Student(std::string n, int s1, int s2, int s3)
        : name(n), score1(s1), score2(s2), score3(s3), total(s1 + s2 + s3) {}
};

int main() {
    int n;
    std::cin >> n;

    std::vector<Student> students;
    students.reserve(n);

    for (int i = 0; i < n; ++i) {
        std::string name;
        int s1, s2, s3;
        std::cin >> name >> s1 >> s2 >> s3;
        students.emplace_back(name, s1, s2, s3);
    }

    // 正确的比较逻辑:a的总分小于b的总分,则a比b小
    auto compare = [](const Student& a, const Student& b) {
        return a.total < b.total;
    };

    std::vector<Student>:: iterator max_student_it = std::max_element(students.begin(), students.end(), compare);

    const Student& max_student = *max_student_it;
    std::cout << max_student.name << " "
              << max_student.score1 << " "
              << max_student.score2 << " "
              << max_student.score3 << std::endl;

    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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