C++:树节点未更新

C++: Tree node not updating

本文关键字:更新 树节点 C++      更新时间:2023-10-16

我正在尝试使用新值更新节点,但是当我在另一个函数中打印出节点时,将显示旧值。我还尝试将"问题"设置为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) {
                  // ^