博客
关于我
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/

    你可能感兴趣的文章
    Python2 已终结,入手Python 3,你需要这30个技巧
    查看>>
    python写下拉列表在excel,无法使用python获取Excel下拉列表(组合框)值
    查看>>
    python2.7安装
    查看>>
    Python2.7安装ncmbot时提示:Microsoft Visual C++9.0 is required
    查看>>
    PYTHON2.Git.1
    查看>>
    python20181211
    查看>>
    Python内存管理机制
    查看>>
    Python2中range 和xrange的区别??
    查看>>
    python2和3的区别
    查看>>
    python2和python3的pip版本升级
    查看>>
    python2和python3的区别
    查看>>
    python2备份交换机配置脚本
    查看>>
    Python3 - 在字符串格式化程序参数中使用变量
    查看>>
    Python3 A*寻路算法实现
    查看>>
    python3 grpc安装
    查看>>
    python3 mysql 封装多表_python3 mysql-多表查询
    查看>>
    python3 mysql8_Python MySQL8.0 错误:authentication plugin 'calling_sha2_password' is not supported....
    查看>>
    Python关键代码总览!从Zero到Hero必看的考点
    查看>>
    python3 robotframework+pycharm框架搭建
    查看>>
    Python3 shutil模块
    查看>>