zoukankan      html  css  js  c++  java
  • C++ 中的sort排序用法

    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;
    }
  • 相关阅读:
    灾后重建
    购物
    [BZOJ3991][SDOI2015]寻宝游戏
    [BZOJ2286][SDOI2011]消耗战
    [Luogu4149][IOI2011]Race
    [BZOJ4003][JLOI2015]城池攻占
    [HDU5765]Bonds
    [HDU5977]Garden of Eden
    [Luogu4331][Baltic2004]数字序列
    [BZOJ4540][HNOI2016]序列
  • 原文地址:https://www.cnblogs.com/luorende/p/6121906.html
Copyright © 2011-2022 走看看