C++ Sort 函数详解

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值