c++ - How can I retrieve a pointer to a variable that is in a list data structure? -
(all of done in c++)
i working tree of nodes. node class variables , list of child-nodes. goal retrieve pointer node x layers down matching on variable.
i aiming create function looks this.
node* node::returnchild(int depth, string match) { ... }
this should recursively iterate down of nodes children , search node variable matching string variable. when finding matching node should take address of node, save in pointer , return functioncall.
i managed make working function iterated down sub-tree of nodes specified depth , found correct node. printed out string value make sure correct node. when trying use node via pointer (provided function) outside of function got nothing.
in function used for-loop looking this:
for(auto fornode : this->children)
this worked fine, seems node "fornode" accessed within scope of loop temporary copy of real node list. copy not "exist" outside of for-loops scope , therefore not able access node located @ pointers address when returned me outside of function (since there no node @ address anymore).
so real question is: how manage pointer "real" node provided list of nodes, depth , matching string?
you'll have switch loop like:
for (auto& fornode : this->children)
this make sure fornode not copied value , invalidated when leave loop scope.
Comments
Post a Comment