sort类函数:ios
函数名 | 功能描述 |
---|---|
sort | 对给定区间全部元素进行排序 |
stable_sort | 对给定区间全部元素进行稳定排序 |
partial_sort | 对给定区间全部元素部分排序 |
partial_sort_copy | 对给定区间复制并排序 |
nth_element | 找出给定区间的某个位置对应的元素 |
is_sorted | 判断一个区间是否已经排好序 |
partition | 使得符合某个条件的元素放在前面 |
stable_partition | 相对稳定的使得符合某个条件的元素放在前面 |
须要头文件<algorithm>less
语法描述:sort(begin,end,cmp),cmp参数能够没有,若是没有默认非降序排序。函数
以int为例的基本数据类型的sort使用this
#include<iostream> #include<algorithm> #include<cstring> using namespace std; int main() { int a[5]={1,3,4,2,5}; sort(a,a+5); for(int i=0;i<5;i++) cout<<a[i]<<' '; return 0; }
由于没有cmp参数,默认为非降序排序,结果为:spa
1 2 3 4 5设计
若设计为非升序排序,则cmp函数的编写:code
bool cmp(int a,int b)对象
{blog
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就足够了,直接拿过来用:
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,greater<int>()); for(i=0;i<20;i++) cout<<a[i]<<endl; return 0; }
引用数据类型string的使用
#include<iostream> #include<algorithm> #include<cstring> using namespace std; int main() { string str("hello world"); sort(str.begin(),str.end()); cout<<str; return 0; }
结果:空格dehllloorw
使用反向迭代器能够完成逆序排序
#include<iostream> #include<algorithm> #include<cstring> using namespace std; int main() { string str("hello world"); sort(str.rbegin(),str.rend()); cout<<str; return 0; }
结果:wroolllhde空格
字符串间的比较排序
#include<iostream> #include<cstring > #include<algorithm> using namespace std; int main() { string a[4]; for(int i=0;i<4;i++) getline(cin,a[i]); sort(a,a+4); for(int i=0;i<4;i++) cout<<a[i]<<endl; return 0; }
以结构体为例的二级排序
#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[4]; for(int i=0;i<4;i++) cin>>x[i].a>>x[i].b; sort(x,x+4,cmp); for(int i=0;i<4;i++) cout<<x[i].a<<' '<<x[i].b<<endl; return 0; }