答案是sort函数在C++中用于高效排序,基于Introsort算法,平均时间复杂度为O(n log n);1. 基本用法:通过传入起始和结束迭代器对数组或vector排序,如sort(arr, arr + n)实现升序排列。

在C++中,sort函数是标准库
1. 基本用法:排序普通数组或vector
使用sort时,需要传入起始和结束迭代器(或指针)。注意:结束位置是不包含的,即左闭右开区间。
- 对数组排序:
#include
#include iostream>
using namespace std;
int main() {
int arr[] = {5, 2, 8, 1, 9};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, arr + n); // 排序整个数组
// 输出: 1 2 5 8 9
for (int i = 0; i
}
- 对vector排序:
#include
vector
sort(vec.begin(), vec.end()); // 升序排列
2. 自定义排序规则:使用比较函数
默认情况下,sort按升序排列。若要改变顺序,可传入第三个参数——比较函数或lambda表达式。
- 降序排序:
sort(vec.begin(), vec.end(), greater
立即学习“C++免费学习笔记(深入)”;
- 自定义比较函数:
bool cmp(int a, int b) {
return a > b; // 降序
}
sort(vec.begin(), vec.end(), cmp);
- Lambda表达式更灵活:
sort(vec.begin(), vec.end(), [](int a, int b) {
return a % 10
});
3. 排序结构体或类对象
当需要对复杂类型排序时,可通过比较函数指定排序依据。
struct Student {
string name;
int score;
};
vector
// 按分数从高到低排序
sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
return a.score > b.score;
});
4. 注意事项与常见错误
使用sort时需注意以下几点,避免出错:
- 确保迭代器有效:不要对空容器或无效范围调用sort
- 比较函数必须满足“严格弱序”:即对于cmp(a,b),若返回true,则a应排在b前面;不能同时cmp(a,b)和cmp(b,a)都为真
- 自定义比较函数应声明为const引用,避免拷贝开销
- 浮点数排序时注意精度问题
基本上就这些。掌握sort的基本调用、自定义规则和结构体排序,就能应对大多数排序需求。记住包含











