本文共 1038 字,大约阅读时间需要 3 分钟。
Sort函数是C++中的一个强大的排序函数,用于对数组或容器中的元素进行排序,默认以升序排列,也可以根据需求设置为降序或其他自定义排序规则。Sort函数采用快速排序算法模板,具有较高的效率,时间复杂度为n*log2(n)。
Sort函数有三个主要形式:
void sort(const RanIt& first, const RanIt& last);void sort(const RanIt& first, const RanIt& last, Pr pred);void sort(RandomAccessIterator first, RandomAccessIterator last, Compare comp);
first:指向数组的起始元素地址。last:指向数组末尾元素的下一个位置,即数组结束的标志。comp(可选):自定义比较函数,用于指定排序规则。如果不需要自定义规则,默认采用升序排序。#include
#include#include using namespace std;int main() { int a[6] = {8, 5, 6, 7, 1, 0}; sort(a, a + 6); for (int i = 0; i < 6; ++i) { cout << a[i] << " "; } return 0;}
运行结果:
0 1 5 6 7 8
bool compare(int a, int b) { return a > b;} 完整代码:
#include#include using namespace std;bool compare(int a, int b) { return a > b;}int main() { int a[6] = {8, 5, 6, 7, 1, 0}; sort(a, a + 6, compare); for (int i = 0; i < 6; ++i) { cout << a[i] << " "; } return 0;}
运行结果:
8 7 6 5 1 0
转载地址:http://zrxzz.baihongyu.com/