Search code examples
c++recursionvectormaze

calling a c++ function with argument that is a reference to vector element


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.


Solution

  • 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.