若是要在Vector容器中存放結構體類型的變量,常常見到兩種存放方式.ios
方式一:放入這個結構體類型變量的副本。spa
方式二:放入指向這個結構體類型變量的指針。.net
假設結構體類型變量是這樣的,3d
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; }
方式一的輸出結果code
/*[方式二] 結構體放入堆中,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; }
方式二的輸出結果,同上,依然是blog
【轉】https://blog.csdn.net/feliciafay/article/details/9128385ci
總結注意:類型的typedef 定義了類型 還須要定義類型的變量get