溫馨提示×

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

c++
小樊
90
2024-07-21 02:12:57
欄目: 編程語言

C++ 的 std::sort 函數(shù)和 lambda 表達(dá)式可以用來對多字段進(jìn)行排序。

假設(shè)我們有一個存儲學(xué)生信息的結(jié)構(gòu)體 Student,其中包含學(xué)生的姓名、年齡和成績:

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

我們可以使用 std::sort 對這個結(jié)構(gòu)體數(shù)組進(jìn)行排序。假設(shè)我們需要首先按照分?jǐn)?shù)降序排序,如果分?jǐn)?shù)相同則按照年齡升序排序,如果年齡也相同則按照姓名字典序排序:

#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 表達(dá)式中我們定義了一個比較函數(shù),根據(jù)分?jǐn)?shù)、年齡和姓名的順序進(jìn)行排序。通過 std::sort 將學(xué)生數(shù)組按照要求排序后,我們可以輸出排序后的結(jié)果。

0