1

我正在遍历树节点的子节点。孩子们存储在 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;
}

为什么这种方法会导致无限递归?谢谢!

4

1 回答 1

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;
}
于 2012-08-15T19:14:04.573 回答