vector容器中存放结构体类型的变量
2018-06-15 15:16
141 查看
如果要在Vector容器中存放结构体类型的变量,经常见到两种存放方式.方式一:放入这个结构体类型变量的副本。方式二:放入指向这个结构体类型变量的指针。假设结构体类型变量是这样的,
- typedef struct student{
- char school_name[100];
- char gender;
- int age;
- bool is_absent;
- } StudentInfo;
那么,方式一和方式二的实现分别如下所示:
[cpp] view plain copy
- /*[方式一] 结构体放栈中,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;
- }
[cpp] view plain copy
- /*[方式二] 结构体放入堆中,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;
- }
方式二的输出结果,同上,依然是
阅读更多
相关文章推荐
- vector容器中存放结构体类型的变量
- Vector容器中存放结构体类型的变量
- C++对存放对象的Vector容器按自定义字段排序
- 【C++ vector】容器类的使用(存放视频帧,生成视频示例)
- 静态vector容器成员变量的定义和初始化
- vector元素为自定义结构体类型时如何对容器元素进行排序?
- vector元素为自定义结构体类型时如何对容器元素进行排序?
- STL概览-序列容器vector,deque,list
- C++容器之 Vector
- 容器:C++vector用法 VS C#list用法
- C++ 9.1 顺序容器-----vector、list、deque
- vector 向量容器
- 容器(vector)、数组、new创建的动态数组,你到底用哪一个(执行效率分析)
- C++ vector容器释放内存应注意的地方(三)
- STL常用容器用法之——vector
- 修改docker镜像,容器存放位置。
- vector容器用法详解
- C++9.5 vector/list/queue容器的区别与选用
- C++标准库容器 vector
- C++ 之 Vector 容器