我正在遍历树节点的子节点。子节点存储在ptr_vector中,在整个迭代过程中的某些时刻我会陷入无限递归,但我无法弄清楚为什么。
这是无限递归发生的方法(此方法仅用于将树结构打印到cout
):
std::ostream& operator<<(std::ostream &strm, const node &n) {
if (n.children_.empty())
return strm << "[]";
for (boost::ptr_vector<node::edge>::const_iterator iter = n.children_.begin(); iter != n.children_.end(); ++iter)
{
if (iter != n.children_.begin())
strm << ", ";
strm << "-" << iter->distance << "->[ " << *(iter->dest) << "]";
}
return strm;
}
这是我正在导航的树结构(请注意,嵌套edge
的目的是表示父节点和子节点之间的距离):
class node
{
public:
node(void);
~node(void);
node* add_child(unsigned int d);
node* get_closest(void);
friend std::ostream& operator<<(std::ostream&, const node&);
private:
class edge
{
public:
edge(node* n, unsigned int d);
~edge(void);
unsigned int distance;
node* dest;
};
boost::ptr_vector<edge> children_;
};
此外,我注意到只有在调用以下方法后才会发生这种无限递归:
node* node::get_closest(void) const
{
if (children_.empty())
return NULL;
boost::ptr_vector<node::edge>::const_iterator iter = children_.begin();
node::edge closest = *iter;
++iter;
if (iter != children_.end())
{
for (; iter != children_.end(); ++iter)
{
if (iter->distance < closest.distance)
closest = *iter;
}
}
return closest.dest;
}
为什么这个方法会导致无限递归? 谢谢!
答案 0 :(得分:0)
根据@ RobI的建议,原始和共享指针的混合导致问题。
我将node::edge closest = *iter;
更改为const node::edge* closest = &(*iter);
。这是该方法的新(和工作)版本:
node* node::get_closest(void) const
{
if (children_.empty())
return NULL;
boost::ptr_vector<node::edge>::const_iterator iter = children_.begin();
const node::edge* closest = &(*iter);
++iter;
if (iter != children_.end())
{
for (; iter != children_.end(); ++iter)
{
if (iter->distance < closest->distance)
closest = &(*iter);
}
}
return closest->dest;
}