学习笔记——sort排序
1.数组排序
sort排序的基本结构:sort(数组名,数组名+数组长度)
头文件:#include<algorithm>
sort排序初始是作为升序排列(小的在前,大的在后)
如果将sort变成降序排列(大的在前,小的在后)
则需自重定义一个cmp函数
bool cmp(int a,int b)
{
return a>b;
}
或者:
bool cmp(int a,int b)
{
if(a>b) return 1;
else return 0;
}
2.结构体数组排序
当我们需要对结构体数组中某个变量进行排序时,我们必须要自定义一个cmp函数
如:
struct p{
int num;
string s;
}a[5];
bool cmp(p x,p y)
{
if(x.num<y.num) return 1;
else return 0;
}
将a数组按num变量从小到大排列
当然,也可以让结构体中别的变量加入排序
struct per{
int num;
int exa;
};
bool cmp(per x,per y)
{
if(x.exa>y.exa)
{
return 1;
}
else
{
if(x.exa==y.exa)
{
if(x.num<y.num)
{
return 1;
}
else
{
return 0;
}
}
else
{
return 0;
}
}
}//P1068
上面代码的意思是,先比较x与y的exa,并让exa较大的在前,若相等,则比较x与y的num,并让num较小的在前.
补充:
若在第一个变量中,填上数组名+n,则sort只会排n后面的
如:
int a[5]={5,2,3,3,2};
sort(a+1,a+5);
排序后变成5,2,2,3,3

浙公网安备 33010602011771号