vector容器中存放结构体类型的变量

如果要在Vector容器中存放结构体类型的变量,经常见到两种存放方式.

方式一:放入这个结构体类型变量的副本。

方式二:放入指向这个结构体类型变量的指针。

假设结构体类型变量是这样的,

typedef struct student{
   char school_name[100];
   char gender;
   int age;
   bool is_absent;
} StudentInfo;

那么,方式一和方式二的实现分别如下所示:

/*[方式一] 结构体放栈中,vector中放副本---------------------*/
#include <iostream>
#include <string>
#include <vector>
typedef struct student{
   char school_name[100];
   char gender;
   int age;
   bool is_absent;
} StudentInfo;
 
typedefstd::vector<StudentInfo> StudentInfoVec;

void print(StudentInfoVec* stduentinfovec){
   for (int j=0;j<(*stduentinfovec).size();j++)
    {
       std::cout<<
           (*stduentinfovec)[j].school_name<<"\t"<<
           (*stduentinfovec)[j].gender<<"\t"<<
           (*stduentinfovec)[j].age<<"\t"<<
           (*stduentinfovec)[j].is_absent<<"\t"<<std::endl;
    }
   return;
}
 
int main(){
   StudentInfo micheal={"Micheal",'m',18,false};
   StudentInfo cherry={"Cherry",'f',16,true};
   StudentInfoVec studentinfovec;
   studentinfovec.push_back(micheal);
   studentinfovec.push_back(cherry);
   print(&studentinfovec);
   return 0;
}
方式一的输出结果

/*[方式二]  结构体放入堆中,vector中放指针---------------------*/
typedef struct student{
   char* school_name;
   char gender;
   int age;
   bool is_absent;
} StudentInfo;
 
typedefstd::vector<StudentInfo*> StudentInfoPtrVec;

void print(StudentInfoPtrVec*stduentinfoptrvec){
   for (int j=0;j<(*stduentinfoptrvec).size();j++)
    {
       std::cout<<
           (*stduentinfoptrvec)[j]->school_name<<"\t"<<
           (*stduentinfoptrvec)[j]->gender<<"\t"<<
           (*stduentinfoptrvec)[j]->age<<"\t"<<
           (*stduentinfoptrvec)[j]->is_absent<<"\t"<<std::endl;
    }
   return;
}

int main(){
 
   StudentInfoPtrVec studentinfoptrvec;
 
   char* p_char_1=NULL;
   p_char_1=new char[100];
   strcpy(p_char_1,"Micheal");
   StudentInfo* p_student_1=new StudentInfo;
   p_student_1->school_name=p_char_1;
   p_student_1->gender='m';
   p_student_1->age=18;
   p_student_1->is_absent=false;
   studentinfoptrvec.push_back(p_student_1);
 
   char* p_char_2=NULL;
   p_char_2=new char[100];
   strcpy(p_char_2,"Cherry");
   StudentInfo* p_student_2=new StudentInfo;
    p_student_2->school_name=p_char_2;
   p_student_2->gender='f';
   p_student_2->age=16;
   p_student_2->is_absent=false;
   studentinfoptrvec.push_back(p_student_2);
      
   print(&studentinfoptrvec);
   delete p_char_1;
   delete p_student_1;
   delete p_char_2;
   delete p_student_2;
   return 0;
 
}


方式二的输出结果,同上,依然是

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值