C++ Sort 函数详解
来源:互联网 发布:怎么在淘宝上卖话费 编辑:程序博客网 时间:2024/06/06 02:46
C++ Sort 函数详解
代码1:
#include <iostream>#include <cstdio>#include <algorithm>using namespace std;bool cmp1(int a,int b){return a<b;}bool cmp2(int a,int b){return a>b;}int main(){int a[8]={2,3,1,4,5,2,3,1};int b[8]={2,3,1,4,5,2,3,1};char c[8]={'a','s','w','a','z','x','s','q'};char d[8]={'a','s','w','a','z','x','s','q'};int f[8]={2,3,1,4,5,2,3,1};char g[8]={'a','s','w','a','z','x','s','q'};sort(a,a+8,cmp1);sort(b,b+8);sort(c,c+8);sort(d,d+8,cmp1);sort(f,f+8,cmp2);sort(g,g+8,cmp2);for(int t=0;t<8;t++)cout<<a[t]<<" "; cout<<endl;for(int t=0;t<8;t++)cout<<b[t]<<" ";cout<<endl;for(int t=0;t<8;t++)cout<<c[t]<<" ";cout<<endl;for(int t=0;t<8;t++)cout<<d[t]<<" ";cout<<endl;for(int t=0;t<8;t++)cout<<f[t]<<" ";cout<<endl;for(int t=0;t<8;t++)cout<<g[t]<<" "; return 0;}
输出:
1 1 2 2 3 3 4 5
1 1 2 2 3 3 4 5
a a q s s w x z
a a q s s w x z
5 4 3 3 2 2 1 1
z x w s s q a a
结论:对于常见数据类型,sort函数比较函数省略,则按照升序进行排序,若有比较函数则根据比较函数进行排序,若比较函数以大于为真则结果降序,若以小于为真则结果升序。
代码2:
#include <iostream>#include <cstdio>#include <algorithm>using namespace std;struct type1{int f;int s;}a[3];bool cmp1(int a,int b){return a<b;}bool cmp2(int a,int b){return a>b;}int main(){a[0].f=1;a[0].s=2;a[1].f=3;a[1].s=4;a[2].f=5;a[2].s=1;sort(a,a+3);for(int t=0;t<3;t++)cout<<a[t].f<<" "<<a[t].s<<" ";return 0;}
结果:编译失败。
结论:结构体函数必须定义比较函数。
代码3:
#include <iostream>#include <cstdio>#include <algorithm>using namespace std;struct type1{int f;int s;}a[4];bool cmp(type1 a,type1 b){if(a.f<b.f) return true;if(a.f>=b.f) return 0;if(a.s<b.s) return true;return false;}int main(){a[0].f=1;a[0].s=2;a[1].f=3;a[1].s=4;a[2].f=2;a[2].s=1;a[3].f=2;a[3].s=5;sort(a,a+4,cmp);for(int t=0;t<4;t++)cout<<a[t].f<<" "<<a[t].s<<endl;return 0;}
输出:
1 2
2 1
2 5
3 4
结论:当仅以主要关键词降序是返回true,结果为升序;同理当仅以关键词升序为true,结果为降序。
阅读全文
0 0
- C qsort和C++ sort函数详解
- sort函数用法详解
- STL sort()函数详解
- c++ sort()函数详解
- C++ Sort 函数详解
- C++sort 函数用法
- C++sort 函数用法
- C++sort 函数用法
- C++Sort函数用法
- C++sort函数
- C/C++sort函数用法
- Python sort sorted函数详解
- Python sort sorted函数详解
- Python sort sorted函数详解
- stl中sort函数详解
- Python sort sorted函数详解
- matlab中的sort函数详解
- python的sort()函数详解
- 暑假集训总结
- SSO 跨域单点登录
- EF6 Code First for MultiContext
- ORACLE索引,索引的建立、修改、删除
- SpringBoot事务注解详解
- C++ Sort 函数详解
- SpringBoot整合Sentry监控项目日志
- Spring Cloud微服务实战pdf
- FFmpeg关于nb_smples,frame_size以及profile的解释 FFmpeg关于nb_smples,frame_size以及profile的解释
- python豆瓣源及模块更新
- sql 行转列 oracle
- 三、初探搜索
- A*算法详解
- StringBoot集成Rabbit,根据业务返回ACK