最常用方法是使用std::sort函数,需包含和头文件。默认升序排序,传入std::greater()可实现降序。对结构体等复杂类型,可通过lambda表达式或自定义比较函数按指定规则排序,如按成绩降序排列学生信息。使用时需确保比较函数满足严格弱序关系。

在C++中,对std::vector进行排序最常用的方法是使用标准库中的std::sort函数。这个函数定义在
包含必要头文件
要使用std::sort,需要包含两个头文件:
-
:用于使用vector容器 -
:提供std::sort函数
基本排序(升序)
默认情况下,std::sort会对vector中的元素按升序排列:
#include#include #include int main() { std::vector vec = {5, 2, 8, 1, 9}; std::sort(vec.begin(), vec.end()); for (int x : vec) { std::cout << x << " "; } // 输出:1 2 5 8 9 return 0; }
降序排序
如果希望按降序排列,可以传入第三个参数std::greater():
立即学习“C++免费学习笔记(深入)”;
std::sort(vec.begin(), vec.end(), std::greater());
这样排序后结果为:9 8 5 2 1。
自定义排序规则
对于复杂类型(如结构体或类),可以通过lambda表达式或自定义比较函数实现特定排序逻辑:
struct Student {
std::string name;
int score;
};
std::vector students = {{"Alice", 85}, {"Bob", 92}, {"Charlie", 78}};
// 按分数从高到低排序
std::sort(students.begin(), students.end(),
[](const Student& a, const Student& b) {
return a.score > b.score;
});
上面的代码使用lambda表达式作为比较函数,实现了按成绩降序排列。
基本上就这些。只要掌握std::sort的基本用法和比较函数的传入方式,就能灵活地对vector进行各种排序操作。注意确保比较函数满足严格弱序关系,避免未定义行为。











