答案是使用函数指针、Lambda表达式、仿函数或结构体重载比较规则实现自定义排序。1. 函数指针用于简单逻辑如降序排列;2. Lambda表达式推荐用于简洁场景如按字符串长度排序;3. 仿函数适用于带状态或复用的复杂逻辑如按绝对值排序;4. 结构体排序通过Lambda比较字段,如先按分数后按姓名排序;需确保比较逻辑满足严格弱序,避免拷贝可使用const引用。

在 C++ 中使用 std::sort 进行自定义排序,关键在于提供一个可调用对象(函数、函数指针、仿函数或 Lambda 表达式)来定义元素之间的比较规则。默认情况下,std::sort 按升序排列,但通过自定义比较函数,可以实现任意排序逻辑。
定义一个返回 bool 类型的函数,接受两个参数,当第一个参数应排在第二个之前时返回 true。
示例:按整数降序排列
#include <algorithm>
#include <vector>
#include <iostream>
bool cmp(int a, int b) {
return a > b; // 降序
}
int main() {
std::vector<int> vec = {3, 1, 4, 1, 5};
std::sort(vec.begin(), vec.end(), cmp);
for (int x : vec) std::cout << x << " ";
// 输出:5 4 3 1 1
}
Lambda 更简洁,适合简单逻辑,可以直接在调用 sort 时定义。
示例:按字符串长度排序
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(),适用于复杂状态或复用场景。
立即学习“C++免费学习笔记(深入)”;
示例:按绝对值排序
struct AbsLess {
bool operator()(int a, int b) {
return abs(a) < abs(b);
}
};
std::vector<int> nums = {-3, 1, -2, 4};
std::sort(nums.begin(), nums.end(), AbsLess());
// 结果:1 -2 -3 4
常用于根据某个字段排序。例如按学生分数或姓名排序。
示例:按成绩降序,成绩相同时按名字升序
struct Student {
std::string name;
int score;
};
std::vector<Student> students = {
{"Bob", 85}, {"Alice", 90}, {"Charlie", 85}
};
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 < b.name; // 名字字典序
});
基本上就这些。只要比较函数满足严格弱序(比如不能出现 a<b 和 b<a 同时为真),就能正确工作。Lambda 最常用,结构体排序也很实用。不复杂但容易忽略细节,比如传引用避免拷贝。基本上掌握这几种方式就够用了。
以上就是c++++怎么自定义排序算法sort_c++ 自定义排序算法方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号