0. 简介
std::sort 是 C++ 标准模板库(STL)中提供的一个排序算法,定义在 <algorithm> 头文件中。它用于对指定范围内的元素进行排序,要求传入的迭代器为随机访问迭代器(如 vector、deque 等)。默认情况下,std::sort 使用元素的 < 运算符进行比较。
以下是关于C++标准库中std::sort
函数的详细教程:
1. 基本用法
#include <algorithm> // 必须包含的头文件
#include <iostream>
#include <vector>
int main() {
int arr[] = {5, 2, 8, 1, 3};
int size = sizeof(arr) / sizeof(arr[0]);
// 对数组排序
std::sort(arr, arr + size);
// 输出结果: 1 2 3 5 8
for(int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
2. 对容器排序
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec = {5, 2, 8, 1, 3};
// 对vector排序
std::sort(vec.begin(), vec.end());
return 0;
}
3. 自定义排序规则
#include <algorithm>
#include <vector>
// 自定义比较函数
bool descending(int a, int b) {
return a > b; // 降序排列
}
int main() {
std::vector<int> vec = {5, 2, 8, 1, 3};
// 使用自定义比较函数
std::sort(vec.begin(), vec.end(), descending);
// 使用lambda表达式
std::sort(vec.begin(), vec.end(), [](int a, int b) {
return a < b; // 升序排列
});
return 0;
}
4. 对结构体/类排序
#include <algorithm>
#include <vector>
struct Person {
std::string name;
int age;
// 重载<运算符
bool operator<(const Person& other) const {
return age < other.age;
}
};
int main() {
std::vector<Person> people = {{"Alice", 25}, {"Bob", 20}, {"Charlie", 30}};
// 方法1: 使用重载的<运算符
std::sort(people.begin(), people.end());
// 方法2: 使用lambda表达式
std::sort(people.begin(), people.end(), [](const Person& a, const Person& b) {
return a.name < b.name; // 按姓名排序
});
return 0;
}
5. 部分排序
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec = {5, 2, 8, 1, 3, 9, 4};
// 只对前4个元素排序
std::sort(vec.begin(), vec.begin() + 4);
// 输出结果: 1 2 5 8 3 9 4
for(int num : vec) {
std::cout << num << " ";
}
return 0;
}
关键点说明:
std::sort
需要#include <algorithm>
- 参数是迭代器范围:
begin()
到end()
- 默认是升序排序
- 时间复杂度:O(N log N)
- 是不稳定排序(如需稳定排序,使用
std::stable_sort
)
需要任何特定方面的更详细解释吗?