C++ 结构体的应用

文章介绍了如何利用C++中的结构体来优化数据存储和排序问题,特别是对于一组具有多个关联属性的数据(如学号和成绩)。通过定义包含学号和成绩的结构体,可以避免使用多个数组并简化排序过程。示例代码展示了如何定义和操作结构体数组,以及实现快速输入输出和自定义排序函数进行排序。
摘要由CSDN通过智能技术生成

结构体是C++中的一种数据类型,它可以让数据的储存、运算、输出更加方便。

就比如说要求对几个学生的成绩进行排序,可是用数组储存的话起码要两个数组:一个储存学号,一个储存成绩。而排序完还要根据成绩顺序的变化而改变学号顺序,不仅麻烦,且时间复杂度、空间复杂度都会更高。

这时,我们就可以用到现在介绍的结构体了。

#include <bits/stdc++.h>
using namespace std;
struct STU{
	int number;
	int score;
}student[100];
inline int read(){
	int x=0,f=1;
	char ch=getchar(); 
	while(ch<'0'||ch>'9'){
		if(ch==' ')return x*f;
		if(ch=='-')f=-1;
		ch=getchar();
	}
    while(ch>='0'&&ch<='9'){
		x=x*10+ch-'0';
		ch=getchar();
	}
return x*f;
}
void write(int x){
	if(x<0)x=-x,putchar('-');
	if(x>9)write(x/10);
	putchar(x%10+'0');
}
bool cmp(STU a,STU b){
	if(a.score==b.score)
		return a.number<b.number;
return a.score>b.score;
}
int main(){
	int n=read();
	for(int i=0;i<n;i++){
		student[i].number=read();
		student[i].score=read();
	}
	sort(student,student+n,cmp);
	for(int i=0;i<n;i++){
		write(student[i].number);
		putchar(' ');
		write(student[i].score);
		putchar('\n');
	}
return 0;
}

结构体很简单,用struct来定义,数组后面跟的就是此个元素的其中一种类型名了,需在struct中定义过。这里用到快读快写,可以自行去网上搜一下。

struct STU{
	int number;
	int score;
}student[100];

看代码片段,定义一个简单的结构体数组的格式为:

struct 结构体名称{
    数据类型 变量名;
}数组名称[元素个数];

这样定义,可以使如student[i]单个元素有student[i].number和student[i].score两项数据,无需定义像student_number[100]和student_score[100]两个数组,且排序更方便、更快捷。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值