子级从父级继承数据的嵌套数据结构
Nested data structure where children inherit data from parent
我正在尝试创建一个嵌套的数据结构,它有很多层深,每个"子"都可以从他们的父/孙等访问数据。。。
以以下数据结构为例:
struct GrandChild {
int someGrandChildData;
};
struct Child {
int someChildData;
std::vector<GrandChild> vgrandChild;
};
struct Parent {
int someParentData;
std::vector<Child> vchild;
};
struct GrandParent {
int someGrandParentData;
std::vector<Parent> vparent;
};
我想访问数据的方式是这样的:
void main()
{
// create and fill in the data
GrandParent gp;
for (int pNum = 0; pNum < 3; pNum++)
{
gp.vparent.push_back(Parent());
for (int cNum = 0; cNum < 3; cNum++)
{
gp.vparent[pNum].vchild.push_back(Child());
for (int gcNum = 0; gcNum < 3; gcNum++)
{
gp.vparent[pNum].vchild[cNum].vgrandChild.push_back(GrandChild());
// call function and ONLY pass a GrandChild
func(gp.vparent[pNum].vchild[cNum].vgrandChild[gcNum]);
}
}
}
}
void func(GrandChild &gc)
{
int result = gc.someGrandChildData;
// no need to pass GrandParent, Parent, or Child because
// GrandChild can access all of the data from them
result += gc.someChildData; // <<-- how can I achieve something like this
result += gc.someParentData; // <<-- how can I achieve something like this
result += gc.someGrandParentData; // <<-- how can I achieve something like this
}
我之所以尝试这样做,是因为我在每个嵌套层都有许多数据成员的结构,当我调用函数时,必须在每个函数调用中传递大量参数,这非常令人讨厌,而且为了保持组织混乱。
如有任何帮助,我们将不胜感激。
您可以通过跟踪每个人的Parent来实现这一点(我们称之为Node)。因此,对于每个节点,在其内部创建其直接父对象的对象,并对每个层(GrandChild、Child、Parent..等)执行此操作。
所以每个GrandChild
将有一个Child
对象,每个Child
将有一个子Parent
对象,并且每个Parent
将有一子GrandParent
对象。
然后你就可以做这样的事情:
void func(GrandChild &gc)
{
int DataFromTheGranChild = gc.DataFromGrandChild;
int DataFromTheChild = gc.Child.DataFromChild;
int DataFromTheParent = gc.Child.Parent.DataFromParent;
int DataFromTheGradParent = gc.Child.Parent.GrandParent.DataFromGrandParent;
//..
}
您可以尝试只使用一种类型的结构。
struct Entity{
int Data;
Entity* Child;
Entity* Parent;
};
相关文章:
- 嵌套结构,从由空行分隔的文件中读取数据
- 嵌套的 STL 数据结构
- 简化C++中的嵌套循环结构
- 将参考类型作为嵌套模板结构中的模板参数作为模板参数不起作用
- 访问嵌套结构的数据成员并将结构传递到功能C
- C 嵌套的数据结构利用结构
- 如何在模板类中使用嵌套的结构/类类型作为返回值
- 如何在 C++ 中将结构类型向量数据输入到结构向量成员(嵌套结构向量)中
- 嵌套的C 常数数据结构,没有初始化列表或明确命名所有节点-VC 2012过早破坏了内部元素
- 访问嵌套结构中的数据
- 类模板中嵌套的结构的构造函数出现问题
- 在C++中嵌套的C结构的offsetof()
- 嵌套类型:结构与类
- 执行方法调用时,有什么理由不C++中添加嵌套类/结构解析
- 链表类,如何访问嵌套节点结构的数据
- 清除嵌套数据
- 防止嵌套的C++结构在父结构为 GC 时被删除
- 尝试处理嵌套对象/结构和动态数组时出现内存泄漏或内存错误。可能的 Xcode/malloc 问题
- 以boost精神分析嵌套数据
- 为什么我不能使用嵌套在结构中的结构作为类型来声明类模板中的变量?