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

    转载于:http://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函数:
    #include <algorithm>
    
    bool compare(int a,int b)
    {
    	return a<b; //升序排列,如果改为return a>b,则为降序
    }
    
    int main()
    {
    	int i;
    	int a[20]={2,4,1,23,5,76,0,43,24,65};
    	
    	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;
    }
    

      

  • 相关阅读:
    Java之IO(一)InputStream和OutputStream
    bitset库
    assert
    C++ 与 Python 混合编程
    C++多线程
    C++11新特性
    C++性能优化指南
    C++随机数
    C++中struct与class的区别
    C++杂记
  • 原文地址:https://www.cnblogs.com/hfultrastrong/p/6428109.html
Copyright © 2011-2022 走看看