【发布时间】:2015-10-12 14:38:38
【问题描述】:
我目前正在编写一个程序,它使用二叉搜索树来存储姓名和电话号码(基本上是电话簿)。我以前用 AVL 树做过这个,它工作得很好。我决定为这个实现切换我的方法,而不仅仅是复制/粘贴最后一个的逻辑和格式。在这样做时,我遇到了一个奇怪的错误,我不知道为什么会这样。一开始我以为我的问题出在我返回结构指针的方式上,但实际上是在我的字符串复制中。
我编写了一个非常基本的程序,它只显示了返回结构的复制函数,然后用数据(从文件中读取)递归地填充 BST。
这是一个简短的例子:
#include <iostream>
#include <string>
using namespace std;
struct Node
{
std::string first;
std::string last;
std::string phone;
};
Node* copyfunc(std::string first, std::string last, std::string phone)
{
Node* temp = NULL;
temp->first = first;
temp->last = last;
temp->phone = phone;
return temp;
}
int main()
{
std::string first, last, phone;
first = "Jenny";
last = "Something";
phone = "8675309";
Node* newStruct = NULL;
newStruct = copyfunc(first, last, phone);
cout << newStruct->first << endl;
cout << newStruct->last << endl;
cout << newStruct->phone << endl;
cout << "Never to be seen again..." << endl;
return 0;
}
现在,我尝试使用 VS2013 调试器找出问题所在,并且它发生在第一个副本上:“temp->first = first;”。它以访问冲突警告中断,然后打开 xstrings(标题?)并指向以下部分:(第 2245 行)
if (this->_Myres < _Newsize)
_Copy(_Newsize, this->_Mysize); // reallocate to grow"
我只是猜测,但据我所知,在我看来,它未能创建新字符串以适应旧字符串长度。
程序(示例和真实程序)将编译,它们只是在到达复制功能时挂起。
感谢所有输入,谢谢!
编辑:我为我的结构使用指针的原因是由于我使用的算法的编写方式。在 BST 中实际将节点链接在一起的函数接受 Node* 类型而不是 Node 对象。 例如:recursiveInsert(Node* root, Node* newNodeToAdd);
【问题讨论】: