C++ 试图删除二叉树并将其移动到 Vector

C++ trying to delete Binary Tree and move it to Vector

所以我正在尝试编写一个函数,将二叉树的所有值放入一个向量中,稍后将用于重新创建它。但是当我尝试调用这个函数时,我得到一个错误:

Error in `./bst': double free or corruption (fasttop):

这是我正在使用的功能。向量本身是一个包含节点的私有变量。 size() returns 树的大小并且正在工作。

void BST::swapvector()
{
    Node *ptr = m_root;
    while (size() != 0)
    {
        if (ptr->m_left != NULL) {
            ptr = ptr->m_left;
        } else if (ptr->m_right != NULL) {
            ptr = ptr->m_right;
        } else {
            Node *temp = ptr;
            myvector.push_back(ptr); //starting from root, we traverse until we reach the bottom and then add ptr to the vector
            ptr = m_root;
            delete temp; //once we're finished, we delete temp
        }
    }
}

有谁知道为什么这不起作用?谢谢!

放置矢量后不能删除temp。另外,你的向量是如何定义的?那里可能有问题。

此外,您应该使用迭代器而不是 push_back() 函数。它不适用于指针。

还有,为什么每个人都坚持使用 C 风格的指针。使用共享或唯一的指针。请?

错误类型通常表示指针被释放两次。

很明显为什么这不起作用。

    } else {
        Node *temp = ptr;
        myvector.push_back(ptr); //starting from root, we traverse until we reach the bottom and then add ptr to the vector
        ptr = m_root;
        delete temp; //once we're finished, we delete temp
    }

您正在将指向 Node 的指针存储到 vector 中,然后使用 delete temp 删除 Node。在存储到向量中的指针指向垃圾或不存在的内存之后。

"...将二叉树的所有值放入向量中的函数..." 不,您不是在存储二叉树值,而是在将 指针 存储到二叉树值(Node 个对象)。

您可以做两件事:

  • 如果二叉树在 myvector 的生命周期内不会被释放或更改,那么您可以删除 delete temp; 行。
  • 如果第一种情况的假设不成立,那么您需要将 Node 个元素存储到 vector 中, 而不是 指向它们的指针。因此,将 myvector 定义为 vector<Node> myvector; 而不是 vector<Node *> myvector; 并将 myvector.push_back(ptr); 更改为 myvector.push_back(*ptr);.