在递归函数中创建std :: list的值,而不是std :: list的指针 [英] Create std::list of value instead of std::list of pointers in recursive function
问题描述
我有这个类:
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);
}
以这种方式,例如:
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;
与 n> = 2
将不会工作(grandson的父代的存储地址 root-> son-> son
- 等等 - 将不是有效的地址,一旦你退出递归函数)。
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).
一个解决这个问题的方法是使用指针列表( list< obj *> children
)而是一个值列表:
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);
}
有另一种方法做同样的工作并存储<$ c $
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?
推荐答案
Isn只是在开始创建更多的孩子之前固定对象的地址的问题?要做到这一点,将它们放在子列表中,然后递归...
Isn't it just a matter of fixing the address of the objects before you start creating further children? To do that, put them into the children list first, then recurse...
void recursive(obj& parent, int n)
{
if (parent.depth == n)
return;
obj son;
son.parent = &parent;
son.depth = parent.depth + 1;
parent.children.push_back(son);
recursive(parent.children.back(), n);
}
这篇关于在递归函数中创建std :: list的值,而不是std :: list的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!