std::sort支持自定义比较函数实现排序,需满足严格弱序规则。可通过函数指针、Lambda表达式(推荐)、函数对象或重载operator<等方式传入比较逻辑。Lambda适用于简洁局部逻辑,如按成绩降序、姓名升序排序学生结构体;函数对象适合复杂或可复用场景;重载operator<可定义类型的自然顺序。选择合适方式并确保比较函数正确性,即可安全高效使用std::sort。

在C++中使用std::sort时,如果需要对自定义类型排序或改变默认的排序规则,可以通过自定义比较函数实现。标准库的std::sort支持多种方式传入比较逻辑,包括函数指针、函数对象(仿函数)、Lambda表达式等。
比较函数必须满足“严格弱序”(Strict Weak Ordering),即:
违反这些规则可能导致程序崩溃或未定义行为。
适用于简单场景,例如按整数降序排列:
立即学习“C++免费学习笔记(深入)”;
bool cmp(int a, int b) {
return a > b; // 降序
}
std::vector<int> nums = {3, 1, 4, 1, 5};
std::sort(nums.begin(), nums.end(), cmp);
Lambda写法简洁,适合局部逻辑。例如对二维点按横坐标升序、纵坐标降序:
std::vector<std::pair<int, int>> points = {{1,2}, {3,4}, {1,5}};
std::sort(points.begin(), points.end(), [](const auto& a, const auto& b) {
if (a.first != b.first)
return a.first < b.first;
return a.second > b.second;
});
假设有一个学生结构体,按成绩降序、姓名升序排列:
struct Student {
std::string name;
int score;
};
std::vector<Student> students = {{"Alice", 85}, {"Bob", 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; // 成绩相同时按名字字典序
});
如果希望类型有自然顺序,可在类内或类外重载 operator<:
bool operator<(const Student& a, const Student& b) {
return a.score < b.score;
}
// 此时可以直接调用 std::sort(students.begin(), students.end());
对于复杂逻辑或需捕获状态的情况,定义函数对象更高效(避免Lambda重复生成):
struct CompareByScore {
bool operator()(const Student& a, const Student& b) const {
return a.score < b.score;
}
};
std::sort(students.begin(), students.end(), CompareByScore{});
基本上就这些。选择哪种方式取决于具体需求:Lambda最常用,函数对象适合复用,operator<适合定义自然序。只要保证比较逻辑符合严格弱序,就能安全使用std::sort。
以上就是C++怎么自定义std::sort的比较函数_C++算法排序与自定义比较函数应用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号