我正在尝试创建一个多层深层的嵌套数据结构,其中每个“子”都可以访问其父/祖父母/等等的数据......
例如采用这些数据结构:
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
}
我正在尝试这样做,因为我在每个嵌套层都有许多数据成员的结构,当我调用函数时,必须将大量参数传递给每个函数调用并且变得混乱以保持组织非常烦人。
非常感谢任何帮助。
答案 0 :(得分:0)
你可以通过跟踪每个人的父(让我们称之为Node)来做到这一点。因此,对于每个Node,在其中创建一个直接Parent的对象,并为每个层(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;
//..
}
答案 1 :(得分:0)
您可以尝试仅使用一种类型的结构。
struct Entity{
int Data;
Entity* Child;
Entity* Parent;
};