sort函数与结构体体排序

*快速排序函数---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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值