温馨提示×

C++ List Sort 对多字段如何排序

c++
小樊
90
2024-07-21 02:12:57
栏目: 编程语言

C++ 的 std::sort 函数和 lambda 表达式可以用来对多字段进行排序。

假设我们有一个存储学生信息的结构体 Student,其中包含学生的姓名、年龄和成绩:

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

我们可以使用 std::sort 对这个结构体数组进行排序。假设我们需要首先按照分数降序排序,如果分数相同则按照年龄升序排序,如果年龄也相同则按照姓名字典序排序:

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

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

int main() {
    std::vector<Student> students = {
        {"Alice", 20, 85.5},
        {"Bob", 22, 90.0},
        {"Alice", 18, 85.5},
        {"Bob", 22, 85.5}
    };

    std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
        if (a.score != b.score) {
            return a.score > b.score;
        } else if (a.age != b.age) {
            return a.age < b.age;
        } else {
            return a.name < b.name;
        }
    });

    for (const auto& student : students) {
        std::cout << student.name << " " << student.age << " " << student.score << std::endl;
    }

    return 0;
}

在 lambda 表达式中我们定义了一个比较函数,根据分数、年龄和姓名的顺序进行排序。通过 std::sort 将学生数组按照要求排序后,我们可以输出排序后的结果。

0