C++:树节点未更新
C++: Tree node not updating
我正在尝试使用新值更新节点,但是当我在另一个函数中打印出节点时,将显示旧值。我还尝试将"问题"设置为updateTree()的返回值,它将返回新的更新节点,但这会产生相同的结果。
void f(Node *n){//n is a pointer that has a string value with a left and right pointer. lets say that "n" right now is "duck"
//do stuff....
updateTree(n);
cout << n->value;//prints out "duck" rather than the updated value..
}
void updateTree(Node *question){
string animal, q;
cout << "Darn, I lost. What was is? ";
getline(cin, animal);
cout << "Enter a question that is true for a(n) " << animal << " and false for a(n) " << question->value << ": ";
getline(cin, q);
Node right(question->value, nullptr, nullptr);//the old animal ie "duck"
Node left(animal, nullptr, nullptr);//the new animal
question = new Node(q, &left, &right);//updated "n" ie "duck" to something else
}
你的代码
void updateTree(Node *question) {
// ^^^^^^ That's a copy of the pointer variable passed.
// Assignments will never affect the original pointer value
// ...
question = new Node(q, &left, &right);
}
将新创建的Node
发送到 void,一旦函数离开范围,它就会丢失。您正在对该指针变量的副本进行操作。
您实际需要的是一个允许更改原始指针的引用:
void updateTree(Node*& question) {
// ^
相关文章:
- 将树节点添加到向量向量中的 n 元树遍历的平均和最坏情况时间复杂度是多少?
- 没有从"树节点"到"树节点*"的可行转换
- 对树节点使用 CString 时出现内存泄漏
- 预分配的节点向量中的无锁树节点分配
- 接受来自键盘的树节点以确定其高度
- C++ Eclipse:二叉搜索树节点>数据=变量似乎不起作用
- C++错误(从不兼容的类型"void"分配给树节点*)
- UWP:在树节点中将文本设置为粗体
- C++/RapidXML:编辑节点并写入新的 XML 文件没有更新的节点
- 树节点之间的最大距离中的运行时错误
- 想要以最新的添加节点完整返回树节点的根
- 从GCC功能树节点中检索函数参数
- 如何映射数组元素以选择二进制树节点
- Boost::p tree - 访问列表中包含的属性树节点
- 二进制搜索树节点插入
- 根据其子节点的余额计算 AVL 树节点余额
- 检查树节点等于值
- 创建一个C++预排序迭代器,为循环提供树节点
- c++ Boost属性树通过属性限定符更新现有节点
- C++:树节点未更新