使用自定义比较函数可控制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<int> nums = {5, 2, 8, 1};
std::sort(nums.begin(), nums.end(), compareDescending);
此时排序结果为:8, 5, 2, 1。
立即学习“C++免费学习笔记(深入)”;
对于简单逻辑,使用 lambda 更简洁,尤其适合局部一次性使用。
示例:对字符串按长度排序:
std::vector<std::string> 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<,这样不传比较函数也能排序。
示例:
struct Person {
std::string name;
int age;
bool operator<(const Person& other) const {
return age < other.age;
}
};
std::vector<Person> 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<std::string> words = {"hello", "world", "code"};
std::sort(words.begin(), words.end(), CompareByLastChar());
按字符串最后一个字符排序。
使用自定义比较函数时,需确保满足严格弱序:即对于任意 a、b、c,满足:
基本上就这些。lambda 最常用,结构体可重载 operator<,复杂逻辑可用仿函数。只要比较函数返回 bool 并定义清楚前后关系,std::sort 就能正确工作。
以上就是c++++中如何自定义排序算法_std::sort自定义比较函数指南的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号