C++ vector排序sort用法_C++ vector自定义排序函数

std::sort 可对 vector 排序,默认升序,支持 greater 降序及自定义比较函数;结构体排序可用函数对象或 lambda 表达式实现灵活规则,需保证严格弱序性。

在C++中,std::vector 是最常用的动态数组容器。当我们需要对 vector 中的元素进行排序时,通常使用 std::sort 函数。这个函数定义在 gorithm> 头文件中,支持默认排序和自定义排序。

默认排序:升序排列

对于基本数据类型(如 int、double、string),可以直接使用 std::sort 进行升序排序。

示例代码:

#include 
#include 
#include 

int main() {
    std::vector nums = {5, 2, 8, 1, 9};
    std::sort(nums.begin(), nums.end());

    for (int x : nums) {
        std::cout << x << " ";
    }
    // 输出:1 2 5 8 9
    return 0;
}

降序排序

如果想按降序排列,可以传入 std::greater() 作为比较函数。

示例代码:

std::sort(nums.begin(), nums.end(), std::greater());
// 结果:9 8 5 2 1

自定义排序函数

当 vector 存储的是自定义结构体或类对象时,需要提供自定义的比较逻辑。

例如:按学生的成绩排序

#include 
#include 
#include 
#include 

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

bool compareByScore(const Student& a, const Student& b) {
    return a.score < b.score;  // 按成绩升序
}

int main() {
    std::vector students = {
        {"Alice", 85},
        {"Bob", 72},
        {"Charlie", 90}
    };

    std::sort(students.begin(), students.end(), compareByScore);

    for (const auto& s : students) {
        std::cout << s.name << ": " << s.score << "\n";
    }
    return 0;
}

Lambda 表达式实现更灵活排序

C++11 支持使用 lambda 表达式,无需额外定义函数,适合临时排序逻辑。

示例:先按成绩降序,成绩相同时按名字升序

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

这种写法简洁且可读性强,特别适用于复杂排序规则。

基本上就这些。掌握 std::sort 配合函数对象或 lambda 的用法,就能灵活处理各种 vector 排序需求。关键是理解第三个参数是“返回 bool 的比较规则”,并且要保证该规则具有严格弱序性。