使用时需要导入头文件<algorithm>

#include<algorithm>

语法描述:sort(begin,end,cmp),cmp参数可以没有,如果没有默认非降序排序。

一.以int为例的基本数据类型的sort使用

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
int a[]={,,,,};
sort(a,a+);
for(int i=;i<;i++)
cout<<a[i]<<' ';
return ;
}

因为没有cmp参数,默认为非降序排序,结果为:

1 2 3 4 5

若设计为非升序排序,则cmp函数的编写:

bool cmp(int a,int b)

{

  return a>b;

}

其实对于这么简单的任务(类型支持“<”、“>”等比较运算符),完全没必要自己写一个类出来。标准库里已经有现成的了,就在functional里,include进来就行了。functional提供了一堆基于模板的比较函数对象。它们是(看名字就知道意思了):equal_to<Type>、not_equal_to<Type>、greater<Type>、greater_equal<Type>、less<Type>、less_equal<Type>。对于这个问题来说,greater和less就足够了,直接拿过来用:

升序:sort(begin,end,less<data-type>());

降序:sort(begin,end,greater<data-type>()).

int  main ( )
{
int a[]={,,,,,,,,,},i;
for(i=;i<;i++)
cout<<a[i]<<endl;
sort(a,a+,greater<int>());
for(i=;i<;i++)
cout<<a[i]<<endl;
return ;
}

二.引用数据类型string的使用

一个字符串间的个字符排序:

使用迭代器可以完成顺序排序

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
string str("hello world");
sort(str.begin(),str.end());
cout<<str;
return ;
}
结果:空格dehllloorw

使用反向迭代器可以完成逆序排序

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
string str("hello world");
sort(str.rbegin(),str.rend());
cout<<str;
return ;
}
结果:wroolllhde空格

字符串间的比较排序

#include<iostream>
#include<cstring >
#include<algorithm>
using namespace std;
int main()
{
string a[];
for(int i=;i<;i++)
getline(cin,a[i]);
sort(a,a+);
for(int i=;i<;i++)
cout<<a[i]<<endl;
return ;
}

三.以结构体为例的二级排序

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
struct link
{
int a,b;
};
bool cmp(link x,link y)
{
if(x.a==y.a)
return x.b>y.b;
return x.a>y.a;
}
int main()
{
link x[];
for(int i=;i<;i++)
cin>>x[i].a>>x[i].b;
sort(x,x+,cmp);
for(int i=;i<;i++)
cout<<x[i].a<<' '<<x[i].b<<endl;
return ;
}

最新文章

  1. 关于i和j
  2. Xcode8以及iOS10问题总结!
  3. postgis数据库文件shapefile导入 dbf file (.dbf) can not be opened.shapefile import failed.
  4. linux笔记:RPM软件包管理-源码包管理
  5. js和jquery的DOM事件大全
  6. cocos2dx中的坐标体系
  7. [原创]使用squish打包与混淆cocos2d-x的lua脚本
  8. Android 文件上传 使用AsyncHttpClient开源框架
  9. Responsive Table 利用@media
  10. vS2010 列表控件 加入右键菜单
  11. CPU最核心的电子元件叫做石英晶振
  12. 海量日志采集系统flume架构与原理
  13. vue-cli搭建项目的目录结构及说明
  14. J.U.C-volatile
  15. maven转gradle ,windows错误重定向
  16. IP,IP地址,mac地址
  17. 使用turtle画故宫(伍奇,侯俊豪小组)
  18. ubuntu 14.04 安装python包psycopg2
  19. Dacapao 实验集(9.12 版本) 能不能给个网址?【内存分析实验】
  20. html 语义化标签拾遗

热门文章

  1. 软件构造 Lab1
  2. Go语言 Note
  3. Day6 - G - 立方体大作战tet HYSBZ - 1106
  4. iPad适配tabBarController
  5. python记事本实现查询替换
  6. 吴裕雄 Bootstrap 前端框架开发——Bootstrap 字体图标(Glyphicons):glyphicon glyphicon-glass
  7. POJ 1458:Common Subsequence
  8. 文本编辑器vim/vi——末行模式
  9. 【WPF学习】第二十四章 基于范围的控件
  10. LCT(2)