【发布时间】:2017-07-26 05:53:50
【问题描述】:
我正在制作一个存储 MechPart 类型项目的二叉搜索树,该树存储一个 int quantity 和一个字符串 code。 MechParts 是通过从文本文件中读取并存储它们的数据而生成的。一个名为 MonthlyUpdate.txt 的单独文本文件用于读取树中的 MechParts 列表,然后更新它们的数量。例如:
MechPart A0001 的数量 = 12
MonthlyUpdate.txt 说 A0001 的数量 = 6
运行更新函数,在树中找到 A0001
将其替换为更新后的数量值 6 (12 - 6)。
这是执行此任务的两个函数:
void DBInterface::updateFromFile(string f_Name)
{
ifstream file (f_Name.c_str());
string line;
MechPart tmp_mp;
if (file.is_open())
{
std::getline(file, line);
while (std::getline (file, line))
{
std::istringstream iss (line);
int q=0;
int pos=0;
pos = line.find('\t',0); //find position of blank space
string tmp_str = line.substr(0,pos); //create a substring
string tmp_str1 = line.substr((pos+1), string::npos);
stringstream ss (tmp_str1);
ss >> q;
tmp_mp.set_code(tmp_str); //set code
tmp_mp.set_quantity(q);
MechPart currentQuantity;
currentQuantity = tree.quantitySearch(tree.getRoot(), tmp_mp);
tmp_mp.set_quantity((currentQuantity.get_quantity()) + q);
tree.update(tree.getRoot(), tmp_mp);
cout << "Current node data: " << tmp_mp.get_code() << " | " << tmp_mp.get_quantity() << endl;
}
}
和 BSTree.template:
template <typename Item>
Item BSTree<Item>::quantitySearch(BTNode<Item>* q_ptr, Item obj)
{
if (q_ptr == NULL)
{
//POINTER IS NULL
}
else if (q_ptr->data() == obj)
{
return q_ptr->data();
}
else if (obj > q_ptr->data())
{ //WORK ON RIGHT SIDE
quantitySearch(q_ptr->get_right(), obj);
}
else
{
//work on left side
quantitySearch(q_ptr->get_left(), obj);
}
}
搜索遍历树并找到具有相同部件名称code 作为参数的MechPart,然后返回该MechPart。
我一直在通过 GDB 调试器运行代码。我让它显示currentQuantity.get_quantity() 以验证返回的MechPart 的数量是否正确,但是由于某种原因我得到了非常大的数字。让我感到困惑的是,在MechPart 构造函数中,它为quantity 分配了一个值0。
最终updateFromFile() 函数给了我一个分段错误,所以这里出了点问题,但我还不能弄清楚是什么。
【问题讨论】:
-
递归搜索时,需要返回找到的节点。您只为一个
if-else块执行此操作。在其他情况下,您将丢弃返回值。 -
有点苛刻。我对此很陌生。
-
@a_pradhan 我不确定你的意思是什么。该函数通过传入的不同节点不断调用自身,直到它到达正确的节点,然后返回它的数据(在本例中为 MechPart)。
-
只有一个控制路径返回值...
标签: c++ templates binary-search-tree