[struct]典型例题 典型应用场景

任务1:按学生总分降序,总分一样,按第一科成绩降序  输出学生姓名

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
struct tstudent {
	string name;
	int score_1;
	int score_2;
	int plus() {return score_1+score_2;}
};
tstudent stu[100];
//tstudent stu[100]={
  {"wang",40,40},{"li",50,50},{"zhang",50,30}};
bool cmp(tstudent a,tstudent b) {
	if(a.plus()!=b.plus())	return a.plus()>b.plus();
	else  return a.score_1>b.score_1;
}
int main() {
    tstudent stux={"test",40,60};
	stu[0].name="wang";	stu[0].score_1=40;	stu[0].score_2=40;
	stu[1].name="li";	stu[1].score_1=50;	stu[1].score_2=50;
	stu[2].name="zhang";	stu[2].score_1=50;	stu[2].score_2=30;

	sort(stu,stu+3,cmp);
	for(int i=0; i<3; i++) {
		cout<<stu[i].name<<"-"<<stu[i].plus()<<" ";
	}
	cout<<endl<<stu[0].name<<":"<<stu[0].plus();
	cout<<endl<<stu[1].name<<":"<<stu[1].plus();
	return 0;
}

任务2:依次输出每个学生的名次

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
struct tstudent {
	string name;
	int index,score,rank;
};
tstudent stu[100];
bool cmp_score(tstudent a,tstudent b) {
	if(a.score!=b.score)		return a.score>b.score;
	else		return a.index<b.index;
}
bool cmp_index(tstudent a,tstudent b) {
	return a.index<b.index;
}
int main() {
	stu[0].index=1;	stu[0].name="wang";	stu[0].score=40;
	stu[1].index=2;	stu[1].name="li";	stu[1].score=50;
	stu[2].index=3;	stu[2].name="zhang";	stu[2].score=35;
	sort(stu,stu+3,cmp_score);
	for(int i=0; i<3; i++) {
		stu[i].rank=i+1;
	}
	sort(stu,stu+3,cmp_index);
	for(int i=0; i<3; i++) {
		cout<<stu[i].rank<<" ";
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值