std::sort是C++ STL中用于高效排序的函数,定义在<algorithm>头文件中,支持基本类型和自定义类型的排序。1. 对基本类型如int、double,默认使用升序排列,可通过std::greater实现降序。2. 对结构体或复杂对象,需提供自定义比较函数,该函数返回bool值表示第一个参数是否应排在第二个之前,例如按学生成绩从高到低排序。3. C++11起推荐使用Lambda表达式实现灵活排序逻辑,如先按分数降序再按名字升序。4. 注意事项包括:比较函数必须满足严格弱序;建议使用const引用避免拷贝;std::sort不保证稳定性,需稳定时用std::stable_sort;仅适用于支持随机访问迭代器的容器如vector,list应使用其成员函数sort。掌握这些用法可应对各类排序需求。

在C++中,std::sort 是 STL 算法库中最常用的排序函数之一。它定义在 <algorithm> 头文件中,可以对数组、vector 等容器中的元素进行高效排序。默认情况下,它按升序排列,但你也可以通过自定义比较函数来控制排序规则。
对 int、double 等基本数据类型排序时,直接使用 std::sort 即可:
#include <algorithm>
#include <vector>
#include <iostream>
<p>int main() {
std::vector<int> nums = {5, 2, 8, 1, 9};
std::sort(nums.begin(), nums.end()); // 升序
// 输出: 1 2 5 8 9</p><pre class='brush:php;toolbar:false;'>std::sort(nums.begin(), nums.end(), std::greater<int>()); // 降序
// 输出: 9 8 5 2 1}
当你需要对结构体、类对象或有特定排序逻辑的数据进行排序时,就需要传入自定义的比较函数。这个函数要返回布尔值,表示第一个参数是否“应该排在”第二个参数之前。
立即学习“C++免费学习笔记(深入)”;
struct Student {
std::string name;
int score;
};
<p>// 自定义比较函数:按分数从高到低排序
bool cmp(const Student& a, const Student& b) {
return a.score > b.score; // 分数高的在前
}</p><p>int main() {
std::vector<Student> students = {
{"Alice", 85},
{"Bob", 92},
{"Charlie", 78}
};</p><pre class='brush:php;toolbar:false;'>std::sort(students.begin(), students.end(), cmp);
// 结果: Bob(92), Alice(85), Charlie(78)}
C++11 起支持 Lambda,写起来更简洁,尤其适合简单排序逻辑:
std::vector<Student> students = {/* ... */};
<p>// 按名字字母顺序排序
std::sort(students.begin(), students.end(),
[](const Student& a, const Student& b) {
return a.name < b.name;
});</p><p>// 先按分数降序,分数相同时按名字升序
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;
});</p>基本上就这些。掌握好自定义比较方式,就能灵活应对各种排序需求了。
以上就是C++ sort函数怎么用_C++ STL排序算法自定义比较函数教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号