mardi 28 mars 2017

How can I retrieve a pointer to a variable that is in a list data structure?

(All of this is done in C++)

I am working with a tree of nodes. The node class is simply some variables and a list of child-nodes. My goal is to retrieve a pointer to a node that is X layers down by matching it on a variable.

I am aiming to create a function that looks something like this.

Node*::Node returnChild(int depth, string match)
{
     ...
}

This should recursively iterate down all of the nodes children and then search for a node with a variable matching the string variable. When finding the matching node it should take the address of the node, save it in a pointer and return it to the functioncall.

I managed to make a working function that iterated down the sub-tree of nodes to the specified depth and found the correct node. It even printed out the string value to make sure that it was the correct node. But when trying to use the node via the pointer (provided by the function) outside of the function I got nothing.

In the function I used for a for-loop looking something like this:

for(auto forNode : this->children)

This worked fine, but it seems that the node "forNode" that is accessed within the scope of the loop is a temporary copy of the real node from the list. This copy does not "exist" outside of its for-loops scope and therefore I will not be able to access the node that was located at the pointers address when it is returned to me outside of the function (since there is no node at the address anymore).

So the real question is: How do I manage to get a pointer to the "real" node provided a list of nodes, the depth and a matching string?

Aucun commentaire:

Enregistrer un commentaire