调用带有引用vector元素参数的c++函数

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

本文关键字:参数 c++ 函数 元素 vector 引用 调用      更新时间:2023-10-16

我正在写一个解决迷宫的c++程序(实际上是解决迷宫的行跟随器)。为此,我声明了一个全局变量:

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

其中node为表示迷宫中实际节点的类。

class node 
{ 
 //members..
};

现在我使用递归来解决迷宫使用函数,

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]);
}

现在我的问题是,如果我对向量node_container元素的引用是正确的,即。'current_node'(即它变得无效),这个问题的解决方法是什么?

一种可能的解决方案是按值传递参数,而不是按引用传递参数,并在每次修改任何节点对象时更新node_container。

但是这真的很乱,我想把它做得干净整洁。

vector调整大小时,引用可能无效。

与其将引用传递给节点本身,不如将vector索引传递给当前节点。

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

然后,访问当前节点,您索引到vector来做。

我认为此时[after push_back]参考变量current_node无效,因为vector刚刚被重新分配。我说的对吗?

是的,你是正确的。vector可能被重新分配,也可能不被重新分配,但由于存在这种可能性,您应该考虑先前的引用无效。

这个问题的解决方法是什么?

如果预先分配了足够的元素,或者使用普通的C数组而不是vector,则引用仍然有效。您必须确保容量足以在最坏的情况下运行,而无需重新分配。

如果总是按顺序访问元素,另一种解决方案可能是使用链表,因为向链表添加元素不会改变对其现有元素的引用。