C++ sort函数自定义排序规则_C++ std::sort比较函数的写法

答案:使用std::sort需提供满足严格弱序的比较函数,可采用普通函数、lambda表达式或函数对象形式,用于自定义排序规则。

在使用 C++ 的 std::sort 函数时,如果要对自定义类型或非默认顺序进行排序,需要提供比较函数。这个比较函数决定了元素之间的“小于”关系,从而控制排序结果。

基本语法与要求

std::sort 定义在 algorithm 头文件中,其常用形式为:

std::sort(begin, end, comp);

其中 comp 是可选的比较函数或函数对象。它必须满足“严格弱序”(Strict Weak Ordering),即对于任意两个元素 a 和 b:

  • 如果 comp(a, b) 返回 true,则 a 应排在 b 前面。
  • 不能同时有 comp(a, b)comp(b, a) 为 true。
  • 若 a 和 b 相等(互不小于对方),它们的相对顺序可能变化(不稳定排序除非特别保证)。

比较函数的三种写法

1. 普通函数

适用于简单场景,比如按整数大小逆序排列:

bool cmp(int a, int b) {
    return a > b; // 降序
}

std::vector vec = {3, 1, 4, 1, 5};
std::sort(vec.begin(), vec.end(), cmp);

也可以用于结构体:

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

bool cmpStudent(const Student& a, const Student& b) {
    return a.score }

2. Lambda 表达式(推荐)

更灵活、可读性强,适合局部逻辑:

std::vector students = {/*...*/};

// 按分数降序,分数相同时按名字字典序升序
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
    if (a.score != b.score)
        return a.score > b.score;
    return a.name });

一行写法(简单情况):

std::sort(vec.begin(), vec.end(), [](int a, int b) { return a

3. 函数对象(仿函数)

适合复杂逻辑或需携带状态的情况:

struct CompareStudent {
    bool operator()(const Student& a, const Student& b) const {
        return a.score     }
};

std::sort(students.begin(), students.end(), CompareStudent{});

常见注意事项

  • 比较函数应返回 bool 类型,且不要修改传入参数(建议用 const 引用)。
  • 避免写成 return a ,这会破坏严格弱序(相等时不应返回 true)。
  • Lambda 中若捕获变量,注意是否影响性能或逻辑。
  • 结构体排序时,优先考虑复合条件下的分支处理。

基本上就这些。掌握这几种写法后,可以应对大多数排序需求。实际开发中推荐使用 lambda,简洁直观。