gpt4 book ai didi

C++:使用递归搜索功能更新二叉搜索树?

转载 作者:行者123 更新时间:2023-11-28 05:59:36 26 4
gpt4 key购买 nike

我正在制作一个存储 MechPart 类型项目的二叉搜索树,它存储一个 int quantity 和一个字符串 code。 MechPart 是通过读取文本文件并存储其数据生成的。名为 MonthlyUpdate.txt 的单独文本文件用于读取树中的 MechPart 列表,然后更新它们的数量。例如:

MechPart A0001's quantity = 12

MonthlyUpdate.txt says A0001's quantity = 6

Run an update function that finds A0001 in the tree

Replace it with the updated quantity value of 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);

}

}

搜索遍历树并找到与参数具有相同零件名称 codeMechPart,然后返回该 MechPart。我一直在通过 GDB 调试器运行代码。我让它显示 currentQuantity.get_quantity() 以验证返回的 MechPart 的数量是否正确,但是由于某种原因我得到了非常大的数字。让我感到困惑的是,在 MechPart 构造函数中,它为 quantity 分配了一个值 0。

最终,updateFromFile() 函数给出了一个段错误,所以这里出现了一些非常错误的情况,但我目前还无法弄清楚是什么。

最佳答案

递归函数需要将递归调用返回给调用者才能正常工作。看看递归的经典阶乘例子:

int factorial(int n) {
if (n == 1) {
return 1;
}
else {
return n*factorial(n-1);
}
}

正如其他人所指出的,您的 quantitySearch 函数仅返回 q_ptr->data() 但从不返回递归 quantitySearch 的返回值> 通话。我将从这里开始,强烈建议在递归函数中添加 cout 语句,以全面了解“幕后”发生的事情

关于C++:使用递归搜索功能更新二叉搜索树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33536812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com