栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++结构体数组详细解析

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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
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 Marrynn";
    char leadername[20];                //该数组为每次输入的候选人的名字
    for(i=0;i<10;i++){                   //循环输入这10个人选的候选人的名字
        cout<<"input name "<        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<    for(i=0;i<3;i++){
       cout<    }  
    cout<<"Abandoned tickets:"<    return 0;
}

当然,如果不使用结构体也可以解决这个问题:
复制代码 代码如下:
#include
#include
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 Marrynn";
 char leadername[20];               
 for(i=0;i<10;i++){                
  cout<<"input name "<  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< for(i=0;i<3;i++){
    cout< }
 cout<<"Abandoned tickets:"< return 0;
}

或者
复制代码 代码如下:
#include
#include
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 Marrynn";
 string leadername;               
 for(i=0;i<10;i++){                
  cout<<"input name "<  cin>>leadername;
  for(j=0;j<3;j++){
   if(leadername==name[j]){
    count[j]++;
    tag=0;
   }
  }
  if(tag==1)k++;
  tag=1;
 }
 cout< for(i=0;i<3;i++){
    cout< }
 cout<<"Abandoned tickets:"< return 0;
}

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/66055.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号