一般,容器vector中存放结构体struct类型的变量,有两种方法::存放结构体类型变量的副本;:存放指向结构体类型变量的指针;
方法/步骤
1、设结构体类型变量为:typedefstructstudent{charschool_name[100];chargender;intage;boolis_absent;}StudentInfo;
2、vector存放结构体类型变量的副本:#inc盟敢势袂lude<iostream>#include<stri荏鱿胫协ng>#include<vector>//structtypedefstructstudent{charschool_name[100];chargender;//xingbieintage;boolis_absent;}StudentInfo;typedefstd::vector<StudentInfo>StudentInfoVec;//shengmingvoidprint(StudentInfoVec*stduentinfovec){for(intj=0;j<(*stduentinfovec).size();j++)//bianlivector{std::cout<<(*stduentinfovec)[j].school_name<<"\t"<<(*stduentinfovec)[j].gender<<"\t"<<(*stduentinfovec)[j].age<<"\t"<<(*stduentinfovec)[j].is_absent<<"\t"<<std::endl;}}intmain(){StudentInfomicheal={"Micheal",'m',18,false};StudentInfocherry={"Cherry",'f',16,true};StudentInfoVecstudentinfovec;//duixiangstudentinfovec.push_back(micheal);studentinfovec.push_back(cherry);print(&studentinfovec);system("pause");return0;}
3、vector存放指向结构体类型变量的指针:#i艘绒庳焰nclude<iostream>#include<stri荏鱿胫协ng>#include<vector>//structtypedefstructstudent{char*school_name;chargender;intage;boolis_absent;}StudentInfo;typedefstd::vector<StudentInfo*>StudentInfoPtrVec;voidprint(StudentInfoPtrVec*stduentinfoptrvec){for(intj=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;}}intmain(){StudentInfoPtrVecstudentinfoptrvec;//duixiangchar*p_char_1=NULL;p_char_1=newchar[100];strcpy(p_char_1,"Micheal");StudentInfo*p_student_1=newStudentInfo;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=newchar[100];strcpy(p_char_2,"Cherry");StudentInfo*p_student_2=newStudentInfo;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);deletep_char_1;deletep_student_1;deletep_char_2;deletep_student_2;system("pause");return0;}