博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
#include <algorithm>中sort的一般用法
阅读量:6858 次
发布时间:2019-06-26

本文共 1442 字,大约阅读时间需要 4 分钟。

1、sort函数的时间复杂度为n*log2(n),执行效率较高。

  2、sort函数的形式为sort(first,end,method)//其中第三个参数可选。

  3、若为两个参数,则sort的排序默认是从小到大,见如下例子

[cpp]
 
  1. #include<iostream>  
  2.   
  3. #include<algorithm>  
  4.   
  5. using namespace std;  
  6.   
  7. int main()  
  8.   
  9. {  
  10.   
  11.   int a[10]={9,6,3,8,5,2,7,4,1,0};  
  12.   
  13.   for(int i=0;i<10;i++)  
  14.   
  15.   cout<<a[i]<<endl;  
  16.   
  17.   sort(a,a+10); //可以看出,两个参数为均地址,a为起始,a+10为结束位置  
  18.   
  19.   for(int i=0;i<10;i++)  
  20.   
  21.   cout<<a[i]<<endl;  
  22.   
  23.   return 0;  
  24.   
  25. }  
#include
#include
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<
<

 

4、若为三个参数,则需要写一个cmp函数(此名称cmp可变),用于判断是从小到大排序还是从大到小排序。   

  (1)需要排序的数组直接为int类型,则见如下例子(从大到小排序)

 

[cpp]
 
  1. #include <algorithm>  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5. bool com(int a,int b)  
  6.   
  7. {  
  8.   
  9.  return a>b;  
  10.   
  11. }  
  12.   
  13. int main()  
  14.   
  15. {  
  16.   
  17.  int a[10]={9,6,3,8,5,2,7,4,1,0};  
  18.   
  19.  for(int i=0;i<10;i++)  
  20.   
  21.  cout<<a[i]<<endl;  
  22.   
  23.  sort(a,a+10,com);//在这里就不需要对com函数传入参数  
  24.   
  25.  for(int i=0;i<10;i++)  
  26.   
  27.  cout<<a[i]<<endl;  
  28.   
  29.  return 0;  
  30.   
  31. }  
#include 
#include
using namespace std;bool com(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<
<

 

(2)如果想依照一个结构体内的一个int型的属性参数进行排序,则见如下例子(从大到小排列)

 

[cpp]
 
    1. #include <iostream>  
    2. #include <algorithm>  
    3.   
    4. using namespace std;  
    5.   
    6. struct node {  
    7.     int a;  
    8.     //.........  
    9.     //  
    10. };  
    11.   
    12. bool cmp(node x,node y)  
    13. {  
    14.      if(x.a != y.a)   
    15.          return (x.a > y.a);  
    16. }  
    17.   
    18. void main(void)  
    19. {  
    20.     int i;  
    21.     node N_t[5];  
    22.     for(i=0; i<5; i++)  
    23.     {  
    24.         cin>>N_t[i].a;  
    25.     }  
    26.     sort(N_t, N_t+5, cmp);  
    27.     for(i=0; i<5; i++)  
    28.     {  
    29.         cout<<N_t[i].a;  
    30.     }  
    31.       
    32. }     

转载地址:http://ykxyl.baihongyu.com/

你可能感兴趣的文章
项目管理学习笔记之中的一个.项目管理综述
查看>>
matlab 工具之各种降维方法工具包,下载及使用教程,有PCA, LDA, 等等。。。...
查看>>
C语言 数组之无限循环
查看>>
List与String的相互转换
查看>>
换行符导致的脚本错误调试
查看>>
Android——Android Sutido:[2]导入eclipse项目篇
查看>>
setsockopt之 TCP_KEEPIDLE/TCP_KEEPINTVL/TCP_KEEPCNT
查看>>
typeid详解
查看>>
SQL Server中的Image数据类型的操作
查看>>
Atitit.html css 浏览器原理理论概论导论attilax总结
查看>>
求解圆圈中最后剩下的数字
查看>>
jQuery入门第二天
查看>>
boost中的智能指针
查看>>
Windows下Php安装mongodb扩展失败
查看>>
discuz安装步骤
查看>>
IntelliJ IDEA修改Output输出缓存区大小【应对:too much output to process】
查看>>
计算机网络概述
查看>>
(转) WTF is computer vision?
查看>>
html标签的target属性应用
查看>>
长连接
查看>>