c++容器存放不同结构的数据
2017-08-27 01:04
197 查看
本来想在c++容器里面存放不同的结构体,但是没有实现,最后通过子类父类的互相转换实现。
只要将建立一个基类的容器就可以直接push子类,这样就实现了一个可以用插入不同数据结构的容器。
cout << "c2:" << static_cast<ChildTwo*>(f_vec->at(1))->flag <<";"<< static_cast<ChildTwo*>(f_vec->at(1))->c2_data << endl;
最后的结果:
c1:I am ChildOne;999
c2:I am ChildTwo;ChildTwo Data
只要将建立一个基类的容器就可以直接push子类,这样就实现了一个可以用插入不同数据结构的容器。
1、将不同的结构体写成同一个基类派生的子类,在子类中添加自己希望的数据类型。
Test.hclass Father { public: std::string flag = "I am Father"; }; class ChildOne :public Father { public: std::string c1_flag = "I am ChildOne"; int c1_data = 999; }; class ChildTwo :public Father { public: std::string c2_flag = "I am ChildTwo"; std::string c2_data = "ChildTwo Data"; };
2、将子类实例化并push到vector(其他容器也可以)
Father * father = new Father(); cout << "father:" << father->flag << endl; ChildOne *c1 = new ChildOne(); cout << "childone:" << c1->flag << endl; ChildTwo *c2 = new ChildTwo(); cout << "childtwo:" << c2->flag << endl; vector<Father*>*f_vec = new vector<Father*>; f_vec->push_back(c1); f_vec->push_back(c2);
3、在需要使用时,将vec中转换成基类的子类转回
cout << "c1:" << static_cast<ChildOne*>(f_vec->at(0))->flag <<";"<< static_cast<ChildOne*>(f_vec->at(0))->c1_data << endl;cout << "c2:" << static_cast<ChildTwo*>(f_vec->at(1))->flag <<";"<< static_cast<ChildTwo*>(f_vec->at(1))->c2_data << endl;
最后的结果:
c1:I am ChildOne;999
c2:I am ChildTwo;ChildTwo Data
4、注意事项
在需要删除容器里的数据时,需要手动将类delete,不然会内存泄漏。
相关文章推荐
- C++容器&数据结构
- c++ 数据容器结构及比较
- C++卷积神经网络实例:tiny_cnn代码详解(11)——层结构容器layers类源码分析
- 【转】C数据存储(包括const存储在哪,C++不同部分我在文中用红字已指出)
- 数据结构(5)线性表之链表C++实现带头结点的单链表合并
- C/C++ 数据结构之算法(面试)
- C++数据结构之单链表
- 数据结构与算法:C++实现插入排序
- 简单数据结构之顺序表(C++ 引用传递实现)
- 数据结构图文解析之:哈夫曼树与哈夫曼编码详解及C++模板实现
- 数据结构知识——树的三种不同遍历算法解析
- C++、数据结构笔试题
- C++读取txt中用不同分隔符分隔的数据
- C++数据结构(0)-----基本概念
- C++ 高级数据类型(五)—— 数据结构
- C/C++中不同数据类型所占用的内存大小
- [置顶] 信息学奥赛一本通(C++版) 第三部分 数据结构 第一章 栈
- C++数据结构——堆,二叉搜索树及Huffman编码输出
- C++之数据结构,单链表
- C++数据结构之实现循环顺序队列