最常用方法是使用std::sort函数。通过#include引入,可对vector进行升序或降序排序;支持基本类型和自定义类型,结合比较函数或Lambda表达式实现灵活排序逻辑。

在C++中对一个vector进行排序,最常用的方法是使用标准库中的std::sort函数。这个函数定义在头文件中,可以高效地对容器元素进行排序。根据元素类型和排序需求,可以使用默认排序规则,也可以自定义比较函数。
基本类型的vector排序
对于存储基本数据类型(如int、double、string等)的vector,可以直接使用std::sort完成升序排序。
#include
#include
#include iostream>
std::vector
std::sort(nums.begin(), nums.end());
// 结果:{1, 2, 5, 8, 9}
若要降序排序,可以传入std::greater()作为比较函数:
std::sort(nums.begin(), nums.end(), std::greater
立即学习“C++免费学习笔记(深入)”;
自定义比较函数
当vector中存储的是自定义类型(如结构体或类),或者需要特定排序逻辑时,需提供自定义比较函数。该函数应返回bool,表示第一个参数是否应排在第二个参数之前。
struct Student {
std::string name;
int score;
};
bool compareStudents(const Student& a, const Student& b) {
if (a.score != b.score) {
return a.score > b.score; // 成绩高的在前
}
return a.name
}
std::vector
std::sort(students.begin(), students.end(), compareStudents);
使用Lambda表达式
C++11起支持Lambda表达式,可更简洁地定义比较逻辑,尤其适合临时排序需求。
// 示例:用Lambda对vector按绝对值升序排序
std::vector
std::sort(values.begin(), values.end(),
[](int a, int b) { return std::abs(a)
// 结果:{1, 2, -3, -5}
注意事项与技巧
使用std::sort时注意以下几点:
- 确保传入的迭代器有效,且区间可随机访问(
vector满足) - 自定义比较函数必须满足“严格弱序”规则,即不能存在循环依赖
- 避免在比较函数中修改对象状态
- 对于大对象,建议使用const引用传参以提升性能
基本上就这些。掌握std::sort配合函数、函数对象或Lambda的使用方式,就能灵活处理各种vector排序需求。不复杂但容易忽略细节,比如比较逻辑的正确性和效率。











