vector容器中存放结构体类型的变量
来源:互联网 发布:君将哀而生之乎的乎 编辑:程序博客网 时间:2024/06/03 22:38
如果要在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; }
方式二的输出结果,同上,依然是
- vector容器中存放结构体类型的变量
- Vector容器中存放结构体类型的变量
- vector容器中存放结构体类型的变量
- vector容器结构体类型查找
- C++中vector容器类型的使用方法
- 结构体容器vector
- vector中不能存放引用类型!!!!!!!!
- c++容器存放不同结构的数据
- C++中在容器Vector中使用结构体Struct
- 存放混合类型对象的JAVA容器
- 结构体中使用容器(vector,list,set...)
- STL中对vector容器中的结构体进行排序
- c++中定义结构体类型变量的方法
- 关于Vector中存放指针的问题
- vector 中存放数组
- 容器中存放的均为副本
- vector元素为自定义结构体类型时如何对容器元素进行排序?
- vector元素为自定义结构体类型时如何对容器元素进行排序?
- IO(IO概述、字符流以及缓冲区)
- Nmap、Netcat、Hping3工具对比
- servlet 处理文件上传的方法【记录】
- java程序员面试中的多线程问题
- .net(c#)提取多层嵌套的JSON
- vector容器中存放结构体类型的变量
- HDOJ 1800 Flying to the Mars 盲目搜索......................so easy...........
- 【白羊座今日运势】
- CDMS系统插件开发介绍
- 线程知识-ThreadLocal使用详解
- datagridview横向纵向合并单元格,重绘实现
- JDBC 学习笔记(一)—— 基础知识 + 分页技术
- javaweb项目的发布
- 关于专业审图公司的CDMS协同解决方案