sort 函数
来源:互联网 发布:加强校园网络建设 编辑:程序博客网 时间:2024/06/05 06:59
sort函数头文件是#include<algorithm>
#include<iostream>#include<algorithm>using namespace std;bool comp( const int a,const int b){ return a>b;}int main(){ int a[5] = {1,2,4,3,5}; sort(a,a + 5);//升序 for(int i = 0;i < 5; i++) cout<<" "<<a[i]; cout<<endl; sort(a,a + 5,comp);//降序 for(int i = 0;i < 5; i++) cout<<" "<<a[i]; cout<<endl; return 0;}
sort函数本身按升序排列。当然可以自己定义一个按降序。如代码。
这个函数可以传两个参数或三个参数。第一个参数是要排序的区间首地址,第二个参数是区间尾地址的下一地址。也就是说,排序的区间是[a,b)。简单来说,有一个数组int a[100],要对从a[0]到a[99]的元素进行排序,只要写sort(a,a+100)就行了,默认的排序方式是升序。如需要对数组t的第0到len-1的元素排序,就写sort(t,t+len);对向量v排序也差不多,sort(v.begin(),v.end());排序的数据类型不局限于整数,只要是定义了小于运算的类型都可以,比如字符串类string。
如果是没有定义小于运算的数据类型,或者想改变排序的顺序,就要用到第三参数——比较函数。比较函数是一个自己定义的函数,返回值是bool型,它规定了什么样的关系才是“小于”。想把刚才的整数数组按降序排列,可以先定义一个比较函数cmp:
0 0
- sort函数
- sort函数
- sort函数
- sort函数
- sort函数
- sort 函数
- sort函数
- sort函数
- sort()函数
- sort函数
- sort函数
- sort函数
- sort函数
- sort函数
- sort函数
- sort函数
- sort函数
- sort函数
- bzoj3209 花神的数论题
- 获取Android手机中所有短信的实现代码
- 面试_java:数组:旋转数组:rotate array(189)
- 【python】numpy,scipy,pandas资源列表
- 手机序列号和设备标识UDID码手机直接获取方式:
- sort 函数
- vagrant系列一:vagrant的安装与初识
- Markdown语法
- relativePath.php
- Coco2d Physics 物理引擎
- Task和Back Stack
- 应用内置embeded tomcat,并打包为fat jar的解决方案
- Maven内置属性及使用
- 生成模型与判别模型