c++++的sort函数需配合自定义比较函数实现灵活排序。默认情况下,sort按升序排列元素,如std::sort(nums.begin(), nums.end())可对vector<int>进行升序排序;要降序排序,可用std::greater<int>()或自定义比较函数;对于结构体或类对象排序,需编写符合要求的比较函数,例如按学生分数从高到低排序可定义bool comparebyscore(const student& a, const student& b) { return a.score > b.score; };若需多条件排序,可在比较函数中添加判断逻辑;c++11后可用lambda表达式简化代码,如std::sort(students.begin(), students.end(), [](const student& a, const student& b) { return a.score > b.score;});此外,要注意比较函数必须满足“严格弱序”,避免未定义行为,并尽量使用引用传递参数以减少拷贝开销,而需要稳定排序时应使用stable_sort。

C++的
sort
<algorithm>
vector

下面我们就来看看怎么用
sort

sort
立即学习“C++免费学习笔记(深入)”;
#include <algorithm>
#include <vector>
std::vector<int> nums = {5, 2, 9, 1, 3};
std::sort(nums.begin(), nums.end());执行后,
nums
{1, 2, 3, 5, 9}
这适用于内置类型(如
int
double
<
想排成从大到小?可以使用标准库提供的
greater<T>
std::sort(nums.begin(), nums.end(), std::greater<int>());
或者你也可以自己写一个比较函数,效果是一样的。
当你要排序的对象不是简单数字,而是结构体、类对象,或者有多个字段要综合判断时,就需要自己写比较函数。
比较函数应该接受两个参数,并返回一个布尔值。如果第一个参数应该排在前面,就返回
true
例如,我们有一个表示学生的结构体:
struct Student {
std::string name;
int score;
};我们希望按分数从高到低排序:
bool compareByScore(const Student& a, const Student& b) {
return a.score > b.score; // 分高的排前面
}然后调用:
std::vector<Student> students = {{"Alice", 80}, {"Bob", 95}, {"Charlie", 70}};
std::sort(students.begin(), students.end(), compareByScore);这样就能得到按成绩降序排列的学生列表。
注意:如果你想先按成绩排,成绩一样再按名字字母顺序排,可以在比较函数里加条件判断:if (a.score != b.score) return a.score > b.score; return a.name < b.name;
C++11以后支持用lambda来写比较函数,不需要单独声明函数,代码更简洁:
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
return a.score > b.score;
});这对临时排序很有帮助,尤其是逻辑不复杂的时候。
sort
stable_sort
基本上就这些内容了。掌握好
sort
以上就是怎样使用C++的algorithm排序函数 sort与自定义比较函数实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号