sort排序
在 C++ 中,std::sort
是标准模板库(STL)中提供的一个非常高效的排序算法。它通常用于对容器中的元素进行排序,比如数组或 std::vector
。std::sort
默认按照升序排序,但你也可以通过提供自定义的比较函数或函数对象来实现降序或其他复杂排序逻辑。
基本用法
#include <iostream>
#include <vector>
#include <algorithm> // 包含 std::sort
int main() {
std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
// 默认升序排序
std::sort(numbers.begin(), numbers.end());
// 输出排序后的结果
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
输出
1 2 5 5 6 9 |
降序排序
要实现降序排序,你可以使用 std::greater<int>()
作为第三个参数,或者使用自定义的比较函数。
使用 std::greater
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
// 降序排序
std::sort(numbers.begin(), numbers.end(), std::greater<int>());
// 输出排序后的结果
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
自定义比较函数
你也可以定义一个自定义的比较函数:
#include <iostream>
#include <vector>
#include <algorithm>
bool compareDescending(int a, int b) {
return a > b; // 如果 a 大于 b,则 a 排在 b 前面
}
int main() {
std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
// 使用自定义比较函数进行降序排序
std::sort(numbers.begin(), numbers.end(), compareDescending);
// 输出排序后的结果
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
注意事项
- 范围:
std::sort
的第一个和第二个参数是指定要排序的范围,通常是容器的begin()
和end()
迭代器。 - 稳定性:
std::sort
不保证稳定性,即对于相等的元素,排序后它们的相对顺序可能改变。如果需要稳定排序,可以使用std::stable_sort
。 - 复杂度:
std::sort
的平均时间复杂度为 O(N log N),其中 N 是要排序的元素数量。
通过这些示例,你可以根据需求灵活使用 std::sort
对数据进行排序。