zoukankan      html  css  js  c++  java
  • sort


    C++ sort()函数的用法

    (一)为什么要用c++标准库里的排序函数 Sort()函数是c++一种排序方法之一,

    学会了这种方法也打消我学习c++以来使用的冒泡排序和选择排序所带来的执行效率不高的问题!
    因为它使用的排序方法是类似于快排的方法,
    时间复杂度为n*log2(n),执行效率较高

    二)c++标准库里的排序函数的使用方法

    I)Sort函数包含在头文件为#include<algorithm>的c++标准库中,
    调用标准库里的排序方法可以不必知道其内部是如何实现的,
    Sort函数有三个参数:
    1)第一个是要排序的数组的起始地址

    2)第二个是结束的地址(最后一位要排序的地址)

    3)第三个参数是排序的方法,可以是从大到小也可是从小到大
    还可以不写第三个参数,此时默认的排序方法是从小到大排序
    Sort函数使用模板: Sort(start,end,排序方法)
    例一:sort函数没有第三个参数,实现的是从小到大
    #include<iostream>
    #include<algorithm>
    using namespace std;
    int main()
    {
    int a[10]={9,6,3,8,5,2,7,4,1,0};
    for(int i=0;i<10;i++)
    cout<<a[i]<<endl;
    sort(a,a+10);
    for(int i=0;i<10;i++)
    cout<<a[i]<<endl;
    return 0;
    }
    需要加入一个比较函数 complare(),
    此函数的实现过程是这样的
    bool complare(int a,int b)
    {
    return a>b;

    }
    这就是告诉程序要实现从大到小的排序的方法!
    #include<iostream>
    #include<algorithm>
    using namespace std;
    bool complare(int a,int b)
    {
    return a>b;
    } int main()
    {
    int a[10]={9,6,3,8,5,2,7,4,1,0};
    for(int i=0;i<10;i++)
    cout<<a[i]<<endl;
    sort(a,a+10,complare);//在这里就不需要对complare函数传入参数了,//这是规则 for(int i=0;i<10;i++) cout<<a[i]<<endl; return 0; }
    ++标准库强大的功能完全可以解决这种麻烦。

    Sort函数的第三个参数可以用这样的语句告诉程序你所采用的排序原则
    less<数据类型>()//从小到大排序 greater<数据类型>()//从大到小排序
    #include<iostream>
    #include<algorithm>
    using namespace std;
    int main()
    {
    int a[10]={9,6,3,8,5,2,7,4,1,0};
    for(int i=0;i<10;i++)
    cout<<a[i]<<endl;
    sort(a,a+10,less<int>());
    for(int i=0;i<10;i++)
    cout<<a[i]<<endl;
    return 0;
    }

    #include<iostream>
    #include<algorithm>
    using namespace std;
    int main()
    {
    int a[10]={9,6,3,8,5,2,7,4,1,0};
    for(int i=0;i<10;i++)
    cout<<a[i]<<endl;
    sort(a,a+10,greater<int>());
    for(int i=0;i<10;i++)
    cout<<a[i]<<endl;
    return 0;
    }
  • 相关阅读:
    xml转义字符在mybatis动态sql中的使用
    jdbc类型与java类型
    aop日志(记录方法调用日志)
    mysql数据库关联查询【lert join】常见使用
    maven项目基本配置
    mapper文件的参数传入与获取
    idea新建项目出现push rejected如何解决
    快速从2个List集合中找出相同/不同元素
    Windows 环境下安装RocketMQ
    RabbitMQ java客户端集成 Spring 开发环境
  • 原文地址:https://www.cnblogs.com/lsb666/p/5682064.html
Copyright © 2011-2022 走看看