您的位置:首页 > 其它

sort函数与结构体体排序

2015-07-24 23:11 330 查看
*快速排序函数---sort的应用模板*/

**************************

#include<algorithm>

using namespace std;

**************************

sort(a,a+k); //两个参数分别为待排序数组的首地址和区间尾地址的【下一地址】,也可以说是数组的长度。可以直接对数组排序,复杂度为n*log2(n),而冒泡为n^2。

默认的排序方式是升序,排序的数据类型不局限于整数,只要是定义了小于运算的类型都可以,比如字符串类string。如果是没有定义小于运算的数据类型,或者想改变排序的顺序,就要用到第三参数——比较函数。比较函数是一个自己定义的函数,返回值是

bool型,自己也可以定义成int形,它规定了什么样的关系才是“小于”。

/*简单例题*/

/*hdu(开门人与关门人)*/
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct stu
{
char a[100];
char b[20];
char c[20];
}z[500];
int cmp1(stu x,stu y)
{
return strcmp(x.b,y.b)<0;
}
int cmp2(stu x,stu y)
{
return strcmp(x.c,y.c)>0;
}
int main()
{
int n,m,i;
scanf("%d",&n);
while(n--)
{
scanf("%d",&m);
for(i=0;i<m;i++)
{
scanf("%s%s%s",z[i].a,z[i].b,z[i].c);
}
sort(z,z+m,cmp1);
printf("%s ",z[0].a);
sort(z,z+m,cmp2);
printf("%s\n",z[0].a);
}
return 0;
}

/*hdu(EXCEL排序)*/

#define M 100001
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct stu
{
char xuehao[10];
char name[10];
int score;
}z[M];
int cmp1(stu x,stu y)
{
return strcmp(x.xuehao,y.xuehao)<0;
}
int cmp2(stu x,stu y)
{
if(strcmp(x.name,y.name)==0)
return strcmp(x.xuehao,y.xuehao)<0;
else return strcmp(x.name,y.name)<0;
}
int cmp3(stu x,stu y)
{
if(x.score==y.score)
return strcmp(x.xuehao,y.xuehao)<0;
else return x.score<y.score;
}
int main()
{
int n,c,i,j,cas;
cas=1;
while(scanf("%d%d",&n,&c)&&c)
{
for(i=0;i<n;i++)
scanf("%s%s%d",z[i].xuehao,z[i].name,&z[i].score);
if(c==1)
sort(z,z+n,cmp1);
else if(c==2)
sort(z,z+n,cmp2);
else if(c==3)
sort(z,z+n,cmp3);
printf("Case %d:\n",cas++);
for(i=0;i<n;i++)
printf("%s %s %d\n",z[i].xuehao,z[i].name,z[i].score);
}
return 0;
}


/hdu*今年暑假不ac*/

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct stu
{
int star;
int end;
}x[101];
int cmp(stu a,stu b)
{
return a.end<b.end;
}
int main()
{
int n,i,j,p,k;
while(scanf("%d",&n)&&n)
{
for(i=0;i<n;i++)
{
scanf("%d%d",&x[i].star,&x[i].end);
}
sort(x,x+n,cmp);
p=x[0].end;k=1;
for(j=1;j<n;j++)
{
if(x[j].star>=p)
{
k++;
p=x[j].end;
}
else continue;
}
printf("%d\n",k);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: