C++中vector排序常用std::sort,配合比较函数或Lambda可实现升序、降序、自定义类型、多条件及部分排序,需注意严格弱序规则。

在C++中,对
vector进行排序最常用的方法是使用标准库中的
std::sort函数。它高效、灵活,配合自定义比较函数或Lambda表达式可以满足各种排序需求。以下是几种实用的
vector排序方法汇总。
1. 基本类型vector的升序排序
对于存储基本类型(如
int、
double等)的
vector,直接使用
std::sort即可完成升序排序。
#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; }
2. 降序排序
可以通过传入
std::greater<>()实现降序排列。
std::sort(vec.begin(), vec.end(), std::greater());
也可以使用Lambda表达式:
立即学习“C++免费学习笔记(深入)”;
std::sort(vec.begin(), vec.end(), [](int a, int b) {
return a > b;
});
3. 自定义对象或结构体排序
若
vector中存储的是自定义结构体,需提供比较规则。
struct Student {
std::string name;
int score;
};
std::vector students = {{"Alice", 85}, {"Bob", 90}, {"Charlie", 70}};
// 按分数从高到低排序
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
return a.score > b.score;
});
如果想按名字字典序排序:
std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
return a.name < b.name;
});
4. 多条件排序
有时需要根据多个字段排序,比如先按成绩降序,成绩相同时按名字升序。
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; // 成绩相同则名字字典序小的在前
});
5. 排序部分元素
如果只想对
vector的一部分排序,可调整迭代器范围。
// 只对前5个元素排序 std::sort(vec.begin(), vec.begin() + 5);
6. 使用自定义比较函数(非Lambda)
也可以定义独立函数作为比较器。
bool compareDescending(int a, int b) {
return a > b;
}
std::sort(vec.begin(), vec.end(), compareDescending);
注意:使用std::sort时,比较函数必须保证“严格弱序”(strict weak ordering),即不能有循环依赖或逻辑矛盾。 基本上就这些。掌握
std::sort搭配Lambda和比较器的用法,就能应对绝大多数
vector排序场景。不复杂但容易忽略细节,比如降序写错符号或Lambda捕获问题。










