结构体数组(C++)

1.定义结构体数组

和定义结构体变量类似,定义结构体数组时只需声明其为数组即可。如:

struct Student{
     int num;
     char name[20];
     char sex[5];
     int age;
     float score;
     char addr[30];
};
Student stu[3]; //定义Student类型的数组stu

2.结构体数组的应用举例

题目:对候选人的票的统计程序。

设有3个候选人,最终只能有一个当选为领导。今有10个人参加投票,从键盘先后输入这10个人所投的候选人的名字,要求最后能输出这3个候选人的的票结果。

#include<iostream>
using namespace std;
struct Person{
    char name[20];                       //姓名 
    int count;                           //票数计数器 
};
int main(){
    Person leader[3]={"Tom",0,"Neo",0,"Marry",0};
                                        //定义Person类型的数组,内容为3个候选人的姓名和票数
    int i,j,k=0;
    bool tag;
    cout<<"please input the name of the leader : Tom Neo Marry\n\n";
    char leadername[20];                //该数组为每次输入的候选人的名字
    for(i=0;i<10;i++){                   //循环输入这10个人选的候选人的名字 
        cout<<"input name "<<i+1<<" :"; 
        cin>>leadername; 
        tag=1;
        for(j=0;j<3;j++){
            if(strcmp(leadername,leader[j].name)==0){
                leader[j].count++;
                tag=0;
            }
        } 
        if(tag==1)k++;
    } 
    cout<<endl;
    for(i=0;i<3;i++){
       cout<<leader[i].name<<":"<<leader[i].count<<endl;    
    }  
    cout<<"Abandoned tickets:"<<k<<endl;
    return 0;
}


当然,如果不使用结构体也可以解决这个问题:

#include<iostream>
#include<string>
using namespace std;
int main(){
	char *name[3]={"Tom","Neo","Marry"};
	int    count[3]={0,0,0};
	int    i,j,k=0;
	bool tag=1;
	cout<<"please input the name of the leader : Tom Neo Marry\n\n";
	char leadername[20];                
	for(i=0;i<10;i++){                 
		cout<<"input name "<<i+1<<" :"; 
		cin>>leadername; 
		for(j=0;j<3;j++){
			if(strcmp(leadername,name[j])==0){
				count[j]++;
				tag=0;
			}
		} 
		if(tag==1)k++;
		tag=1;
	} 
	cout<<endl;
	for(i=0;i<3;i++){
	   cout<<name[i]<<":"<<count[i]<<endl;	
	}
	cout<<"Abandoned tickets:"<<k<<endl;
	return 0;
}

或者

#include<iostream>
#include<string>
using namespace std;
int main(){
	string name[3]={"Tom","Neo","Marry"};
	int    count[3]={0,0,0};
	int    i,j,k=0;
	bool tag=1;
	cout<<"please input the name of the leader : Tom Neo Marry\n\n";
	string leadername;                
	for(i=0;i<10;i++){                 
		cout<<"input name "<<i+1<<" :"; 
		cin>>leadername; 
		for(j=0;j<3;j++){
			if(leadername==name[j]){
				count[j]++;
				tag=0;
			}
		} 
		if(tag==1)k++;
		tag=1;
	} 
	cout<<endl;
	for(i=0;i<3;i++){
	   cout<<name[i]<<":"<<count[i]<<endl;	
	}
	cout<<"Abandoned tickets:"<<k<<endl;
	return 0;
}

但是,相比较使用结构体的方法,我们对于候选人和票数的关系,更加直观,联系更加明显。



转载于:https://www.cnblogs.com/zhezh/p/3773528.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值