我正在遍历树节点的子节点。子项存储在一个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;
}
为什么此方法会导致无限递归?谢谢!
根据@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;
}