MST

星途 面试题库

面试题:C++ 中 STL算法sort的自定义排序规则应用

假设有一个结构体 `Student`,包含 `name`(字符串类型)和 `score`(整数类型)两个成员变量。要求使用 `std::sort` 对一个 `Student` 类型的数组进行排序,排序规则为按 `score` 从高到低排序,如果 `score` 相同,则按 `name` 的字典序从小到大排序。请编写相应的代码实现。
46.4万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <algorithm>
#include <string>

struct Student {
    std::string name;
    int score;
};

bool compare(const Student& a, const Student& b) {
    if (a.score != b.score) {
        return a.score > b.score;
    } else {
        return a.name < b.name;
    }
}

int main() {
    Student students[] = {{"Alice", 85}, {"Bob", 90}, {"Charlie", 85}, {"David", 78}};
    int size = sizeof(students) / sizeof(students[0]);

    std::sort(students, students + size, compare);

    for (int i = 0; i < size; ++i) {
        std::cout << "Name: " << students[i].name << ", Score: " << students[i].score << std::endl;
    }

    return 0;
}