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

在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。
立即学习“C++免费学习笔记(深入)”;
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
以上就是c++++中如何自定义排序算法_std::sort自定义比较函数指南的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1476094.html
微信扫一扫
支付宝扫一扫