答案:c++中对vector排序最常用sort函数,需包含<algorithm>头文件。默认升序,可传greater<T>实现降序,或用自定义比较函数、Lambda表达式处理复杂逻辑,如结构体按成员排序。注意区间为左闭右开,时间复杂度O(n log n),空vector安全调用,自定义比较需满足严格弱序。

在C++中,对vector进行排序最常用的方法是使用标准库中的sort函数。该函数定义在头文件
1. 基本用法:默认升序排序
对于存储基本数据类型的vector(如int、double、String等),可以直接使用sort进行升序排序。
#include <vector>
#include <algorithm>
#include <iostream>
using Namespace std;
int main() {
vector<int> nums = {5, 2, 8, 1, 9};
sort(nums.begin(), nums.end()); // 升序排序
for (int x : nums) {
cout << x << ” “;
}
// 输出:1 2 5 8 9
return 0;
}
2. 降序排序
如果需要降序排列,可以传入第三个参数greater<T>,或者使用自定义比较函数。
#include <functional> // for greater
sort(nums.begin(), nums.end(), greater<int>()); // 降序
此时输出为:9 8 5 2 1
立即学习“C++免费学习笔记(深入)”;
3. 自定义排序规则
当vector中存储的是自定义类型(如结构体)或需要特殊排序逻辑时,可以传入一个比较函数或lambda表达式。
Struct Student {
string name;
int score;
};
bool cmp(const Student& a, const Student& b) {
return a.score > b.score; // 按分数从高到低排序
}
int main() {
vector<Student> students = {{“Alice”, 85}, {“Bob”, 90}, {“Charlie”, 70}};
sort(students.begin(), students.end(), cmp);
for (const auto& s : students) {
cout << s.name << “: ” << s.score << endl;
}
return 0;
}
也可以使用lambda表达式实现相同功能:
sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
return a.score > b.score;
});
4. 注意事项与技巧
使用sort时需注意以下几点:
- 确保包含头文件<algorithm>
- sort的时间复杂度为O(n log n),适用于大多数场景
- 区间为左闭右开:[begin, end)
- 若vector为空,调用sort不会出错
- 对于类类型,确保比较函数是“严格弱序”(即不能有相等返回true的情况)
基本上就这些。掌握sort的基本和自定义用法,就能灵活处理vector的各种排序需求。不复杂但容易忽略细节,比如greater要加括号、自定义函数参数类型要加const引用等。写多了就顺了。