记录PTA甲级以及C++部分语法知识1055-结构体向量排序

自己写的时候发现一个问题,printf不可以用来输出vector中的结构体元素!!!

其他也没啥了,但是还有一个case超时。

超时是因为进行了多次sort,这样如果查询的range很多的话,就会浪费很多时间,不足以弥补使用多个向量存储节省的查询年龄的时间。

推荐一版:https://blog.csdn.net/xtzmm1215/article/details/39019739

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>

using namespace std;

struct person{
	int worth;
	int age;
	string name;
};

bool cmp(person p1,person p2){
	if(p1.worth==p2.worth){
		if(p1.age==p2.age){
			return p1.name<p2.name;
		}
		else
			return p1.age<p2.age;
	}
	else
		return p1.worth>p2.worth;
}

vector<person> P[200];
vector<person> res;

int main(){
	int N,K,i;
	scanf("%d%d",&N,&K);
	char name[9];
	int age,worth;
	for(i=0;i<N;i++){//不能直接scanf string,至少要string.resize(9),但是这样又固定大小了。。。
		scanf("%s %d %d",&name,&age,&worth);
		person p;
		p.name=name;
		p.age=age;
		p.worth=worth;
		P[age].push_back(p);

		
	}

	int amont,s,e,k,t,j;
	for(i=0;i<K;i++){
		res.clear();
		scanf("%d %d %d",&amont,&s,&e);
		for(j=s;j<=e;j++){
			for(k=0;k<P[j].size();k++)
				res.push_back(P[j][k]);
				
		}
		
		sort(res.begin(),res.end(),cmp);
		
		
		printf("Case #%d:\n",i+1);
		for(t=0;t<amont&&t<res.size();t++){
			//printf("%s %d %d\n",res[t].name,res[t].age,res[t].worth);//***printf不可用于输出vector的元素!!!!
			cout<<res[t].name<<" "<<res[t].age<<" "<<res[t].worth<<endl;
		}
		if(res.size()==0)
			cout<<"None"<<endl;
	}



	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值