zoukankan      html  css  js  c++  java
  • C++ sort

    原文链接:https://www.cnblogs.com/luorende/p/6121906.html
    STL
    中就自带了排序函数sortsort 对给定区间所有元素进行排序 要使用此函数只需用#include <algorithm> sort即可使用,语法描述为:
    sort(begin,end),表示一个范围,例子:#include <algorithm>int main()
    {
    int a[20]={2,4,1,23,5,76,0,43,24,65},i;
    for(i=0;i<20;i++)
    cout<<a[i]<<endl;
    sort(a,a+20);
    for(i=0;i<20;i++)
    cout<<a[i]<<endl;
    return 0;
    }
    输出结果将是把数组a按升序排序,说到这里可能就有人会问怎么样用它降序排列呢?这就是下一个讨论的内容.
    一种是自己编写一个比较函数来实现,接着调用三个参数的sort:sort(begin,end,compare)就成了。对于list容器,这个方法也适用,把compare作为sort的参数就可以了,即:sort(compare).

    1)自己编写compare函数:
    bool compare(int a,int b)
    {
    return a<b; //升序排列,如果改为return a>b,则为降序
    }#include <algorithm>
    int main()
    {
    int a[20]={2,4,1,23,5,76,0,43,24,65},i;
    for(i=0;i<20;i++)
    cout<<a[i]<<endl;
    sort(a,a+20,compare);
    for(i=0;i<20;i++)
    cout<<a[i]<<endl;
    return 0;
    }
     
  • 相关阅读:
    springboot模板
    springboot入门
    java自定义注解
    git集成idea
    git的搭建和使用
    Shiro授权
    shiro认证
    shiro入门
    springmvc文件上传
    springmvc入门
  • 原文地址:https://www.cnblogs.com/renzmin/p/11871913.html
Copyright © 2011-2022 走看看