c++ - C ++试图删除二叉树并将其移动到Vector
问题描述
所以我正在尝试编写一个函数,将二叉树的所有值放入一个向量中,稍后将使用该向量重新创建它。但是当我尝试调用这个函数时,我得到一个错误:
Error in `./bst': double free or corruption (fasttop):
这是我正在使用的功能。向量本身是一个包含节点的私有变量。size() 返回树的大小并且正在工作。
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
}
}
}
有谁知道为什么这不起作用?谢谢!
解决方案
很明显为什么这不起作用。
} 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
到向量中,然后Node
用delete temp
. 之后存储到向量中的指针指向垃圾或不存在的内存。
“......一个将二叉树的所有值放入向量中的函数......”
不,您不是在存储二叉树值,而是在存储指向二叉树值(Node
对象)的指针。
你可以做两件事:
- 如果二叉树在其生命周期内不会被释放或更改,
myvector
那么您可以删除该delete temp;
行。 - 如果第一种情况的假设不正确,那么您需要将
Node
元素存储到向量中,而不是指向它们的指针。因此,定义myvector
为vector<Node> myvector;
代替vector<Node *> myvector;
并更改myvector.push_back(ptr);
为myvector.push_back(*ptr);
。
推荐阅读
- python - 获取NxN网格python的邻居
- java - 递归方法在android中不起作用
- hugo - 如何禁止相关内容显示在我的帖子中
- xml - 从 XSLT 生成新的 XML
- swift - Firebase 身份验证错误代码 33 FIRAuthInternalErrorDomain 是什么意思?
- jquery - jQuery切换标签内容
- json - 合并多个 JSON 文件(两个以上)
- go - 如何通过 Go 的 MaxBytesReader 确定我是否已达到大小限制
- python - Pandas DataFrame:列 cumsum 除以迄今为止的行和列总和
- javascript - 如何将百分比列添加到 dc.js 数据表?