I have this class:
class obj
{
public:
obj()
: parent(nullptr),
depth(0)
{ }
obj* parent;
list<obj> children;
int depth; // Used only for this example
};
And to fill my data structure I use a recursive function like the following:
void recursive(obj& parent)
{
if(parent.depth == 1)
return;
obj son;
son.parent = &parent;
son.depth = parent.depth + 1;
recursive(son);
parent.children.push_back(son);
}
In this way for example:
obj root;
recursive(root);
If you pay attention you can see that if the test in the recursive funcion had been:
if(parent.depth == n)
return;
with n >= 2
this code will not work (the stored address of the parent of the "grandson" root->son->son
- and so on - will be not a valid address once you exit the recursive function).
One way to solve this problem is use a list of pointers (list<obj*> children
) instead a list of value:
void recursive(obj& parent)
{
if(parent.depth == 2)
return;
obj* son_ptr = new obj();
son_ptr->parent = &parent;
son_ptr->depth = parent.depth + 1;
recursive(*son);
parent.children.push_back(son_ptr);
}
Is there another way to do the same work and store the obj
s in a list of value instead of in a list of pointers?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…