博客
关于我
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-如何使用FastAPI和uvicorn.run而不阻塞线程?
    查看>>
    Python-字典
    查看>>
    python-字符串
    查看>>
    Python-将二进制遮罩转换为多边形
    查看>>
    python-文件操作
    查看>>
    PYTHON-模块 sys os random shutil-练习
    查看>>
    Python-模块与包的管理
    查看>>
    PYTHON-模块定义 搜索路径
    查看>>
    Python-爬虫工程师-面试总结
    查看>>
    Python-类与文件读取结合
    查看>>
    python-类思想-实现简单增删查改
    查看>>
    python-网络编程
    查看>>
    python写入文件出现空行
    查看>>
    PYTHON-返回给定x的多边形路径的y坐标
    查看>>
    python-进程池与线程池,协程
    查看>>
    Python-通过函数传递变量
    查看>>
    Python内置函数详解——总结篇
    查看>>
    Python.对象集合中的标识.和散列
    查看>>
    Python.硒.拖放错误“AttributeError:move_to 需要 WebElement“
    查看>>
    Python内置函数详解
    查看>>