商城首页欢迎来到中国正版软件门户

您的位置:首页 >C++自定义排序方法及sort比较函数详解

C++自定义排序方法及sort比较函数详解

  发布于2025-12-12 阅读(0)

扫一扫,手机访问

使用自定义比较函数可控制std::sort排序规则。1. 函数指针:定义bool compare(int a, int b)实现降序;2. Lambda表达式:按字符串长度升序排序,语法更简洁。

c++中如何自定义排序算法_std::sort自定义比较函数指南

在C++中使用 std::sort 时,可以通过自定义比较函数来控制排序的规则。这在处理复杂数据类型或需要特定排序逻辑时非常有用。下面介绍几种常见的自定义比较方式,并说明使用要点。

函数指针作为比较函数

最基础的方式是定义一个返回 bool 类型的函数,接收两个参数,用于判断第一个是否应排在第二个之前。

示例:

对整数按降序排序:

bool compareDescending(int a, int b) {
    return a > b;  // a 排在 b 前面当 a > b
}

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

此时排序结果为:8, 5, 2, 1。

Lambda 表达式(推荐)

对于简单逻辑,使用 lambda 更简洁,尤其适合局部一次性使用。

示例:

对字符串按长度排序:

std::vector words = {"apple", "hi", "banana", "go"};
std::sort(words.begin(), words.end(),
    [](const std::string& a, const std::string& b) {
        return a.length() < b.length();
    });

排序后顺序为:"hi", "go", "apple", "banana"。

重载 operator<

如果自定义类有自然顺序,可以在类内重载 operator<,这样不传比较函数也能排序。

示例:
struct Person {
    std::string name;
    int age;

    bool operator<(const Person& other) const {
        return age < other.age;
    }
};

std::vector people = {{"Alice", 30}, {"Bob", 25}};
std::sort(people.begin(), people.end()); // 按年龄升序

仿函数(函数对象)

适用于需要状态或复用的场景。定义一个类并重载 operator()

示例:
struct CompareByLastChar {
    bool operator()(const std::string& a, const std::string& b) const {
        return a.back() < b.back();
    }
};

std::vector words = {"hello", "world", "code"};
std::sort(words.begin(), words.end(), CompareByLastChar());

按字符串最后一个字符排序。

使用自定义比较函数时,需确保满足严格弱序:即对于任意 a、b、c,满足:

  • 不可同时有 comp(a,b) 和 comp(b,a)
  • 若 comp(a,b) 且 comp(b,c),则必须有 comp(a,c)
  • comp(a,a) 必须为 false

基本上就这些。lambda 最常用,结构体可重载 operator<,复杂逻辑可用仿函数。只要比较函数返回 bool 并定义清楚前后关系,std::sort 就能正确工作。

本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注