博客
关于我
C++ sort()函数使用简介
阅读量:531 次
发布时间:2019-03-05

本文共 1015 字,大约阅读时间需要 3 分钟。

Sort函数简介

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/

    你可能感兴趣的文章
    Python:TypeError:无法连接“str“和“int“对象
    查看>>
    Python:XPath 在 ElementTree 中不可用
    查看>>
    Python:从 FTP 服务器下载文件
    查看>>
    python:从列表中创建元组列表
    查看>>
    Python:从嵌套列表中删除重复项
    查看>>
    Python:从间隔映射到值
    查看>>
    Python:使用 shell=False 的子进程调用不起作用
    查看>>
    Python:修改 PATH 环境变量的平台无关方式
    查看>>
    Python:假与 0
    查看>>
    Python:函数使用
    查看>>
    Python:函数进阶
    查看>>
    Python:在整数的二进制表示中查找最长的二进制间隙
    查看>>
    Python:如何从二进制转换为 base 64 并返回?
    查看>>
    Python:如何以非阻塞方式读取子进程的标准输出
    查看>>
    Python:如何使用 plotly 制作阴影区域或交替背景颜色?
    查看>>
    Python:如何根据日期时间获取值的计数
    查看>>
    python:如何检测串行 COM 上的设备名称/ID
    查看>>
    Python:如何模拟 datetime.utcnow()?
    查看>>
    Python:如果DataFrames之间的其他值匹配,则对DataFrame中的值求和
    查看>>
    Python:字典思维
    查看>>