I am writing a c++ program for solving maze (actually for maze solving line follower). For that I declared a global variable:

vector< node > node_container  // to contain each node encountered 
                              //  with its latest info. 

where node is a class indicating actual node in maze .

class node 
{ 

 //members..

};

now i am using recursion to solve the maze using the function,

void node_action(node & current_node)      
// will be called with argument node_container[0] for the first time  
{

//do some works first...then

if(new_node_found == true)
{      
 node new_node;

 node_container.push_back(new_node);

 // i think at this point reference variable current_node becomes invalid     
// because the vector is just reallocated . am i correct ?

//here new node becomes current node and node_action() function is called for it now 

node_action(node_container[(node_container.size())-1]); 

//return to our first node i.e. for which this version of node_action() is called.       
// but i think 'current_node' is no more that what i want it to be 

}

} // end of node_action()     

int main()
{

 node first ;        
 node_container.push_back(first);      
 node_action(node_container[0]);

}

Now my question is if I am correct with the reference to element of vector node_container i.e. 'current_node' (i.e. it becomes invalid ), whats the way around of this problem?

One possible solution may be passing the argument by value, not by reference and update the node_container every time any node object is modified.

But this is really a messy way and I want to do it net and clean.

有帮助吗?

解决方案

The reference may become invalid when the vector is resized.

Instead of passing in the reference to the node itself, it is safer to pass in the vector index to the current node.

void node_action(int current_node)      
{
    //...
    node_action(node_container.size()-1);

}

//...
node_action(0);

Then, to access the current node, you index into vector to do it.

其他提示

I think at this point [after push_back] reference variable current_node becomes invalid, because the vector is just reallocated. Am I correct?

Yes, you are correct. The vector may or may not be reallocated, but since there is a possibility, you should consider the prior reference invalidated.

What's the way around of this problem ?

If you pre-allocated enough elements upfront, or use a plain C array instead of a vector, the reference would remain valid. You must ensure that the capacity is sufficient for the worst-case scenario to run without re-allocations.

If you always access the elements sequentially, another solution could be using a linked list, because adding elements to a linked list do not change references to its existing elements.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top