4

我创建了一个函数来将现有的树对象转换为字符串。字符串的格式是

parent ( child1 ) ( child2 ( childOfChild2 ) )

程序正确输出字符串,做一些其他的工作,但在和崩溃

Segmentation fault (core dumped)

这是函数(getTree(this->root)输出整棵树):

template <typename T>
string Tree<T>::getTree(const Node<T>& node) {
    if (node.isLeaf()){
        return to_string(node.value);
    }

    vector<future<string>> results; //each element represents a subtree connected to "node"
    for (auto child:node.children){
        results.push_back(move(async(&Tree<T>::getTree,this,ref(*child))));
    }

    string children("");
    for (auto& result:results){
        children+=string(" (") + result.get()+ string(") ");     //this creates Segmentation fault, but the output is correct
        //children+=string("");                                  //this does not create Segmentation fault
        //children+=string("foo");                               //this creates Segmentation fault
    }

    return to_string(node.value)+children;
}  

关于变量的一些信息:

vector<shared_ptr<Node>> children;

请告诉您是否需要更多信息。完整的源代码是tree.cpptree.h

4

1 回答 1

1

您在迭代器中的比较功能不起作用 - 您还需要涵盖两个容器均为空的情况,即

bool operator!= (const Iter& other) const {
    if (this->queueToIter.empty()&& other.queueToIter.empty()) return false;
    if (this->queueToIter.empty()&&! other.queueToIter.empty()) return true;
    if (!this->queueToIter.empty()&& other.queueToIter.empty()) return true;
    return (this->queueToIter.front())!=(other.queueToIter.front());
};
于 2012-10-26T08:41:31.190 回答