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,结果为降序。