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

在C++中,sort函数是标准库
使用sort时,需要传入起始和结束迭代器(或指针)。注意:结束位置是不包含的,即左闭右开区间。
#include <algorithm>
#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
}
#include <vector>
vector<int> vec = {4, 2, 7, 3};
sort(vec.begin(), vec.end()); // 升序排列
默认情况下,sort按升序排列。若要改变顺序,可传入第三个参数——比较函数或lambda表达式。
sort(vec.begin(), vec.end(), greater<int>()); // 使用内置函数对象
立即学习“C++免费学习笔记(深入)”;
bool cmp(int a, int b) {
return a > b; // 降序
}
sort(vec.begin(), vec.end(), cmp);
sort(vec.begin(), vec.end(), [](int a, int b) {
return a % 10
});
当需要对复杂类型排序时,可通过比较函数指定排序依据。
struct Student {
string name;
int score;
};
vector<Student> students = {{"Alice", 85}, {"Bob", 90}, {"Charlie", 78}};
// 按分数从高到低排序
sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
return a.score > b.score;
});
使用sort时需注意以下几点,避免出错:
基本上就这些。掌握sort的基本调用、自定义规则和结构体排序,就能应对大多数排序需求。记住包含<algorithm>头文件,合理使用lambda表达式,代码会更简洁清晰。
以上就是c++++怎么使用sort函数排序_C++标准库sort函数使用全攻略的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号