3

我正在编写一个用于解决迷宫的 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。

但这真的是一种凌乱的方式,我想把它弄干净……

我想说我不是很有经验的程序员,所以如果你详细说明你的答案会更有帮助。先谢谢了...

4

2 回答 2

2

我认为此时 [after push_back] 引用变量current_node变得无效,因为vector刚刚重新分配。我对么?

是的,你是对的。可能会vector或可能不会重新分配,但由于有可能,您应该考虑先前的引用无效。

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

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

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

于 2013-06-19T02:29:59.590 回答
2

调整大小时,引用可能会变得无效vector

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

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

}

//...
node_action(0);

然后,要访问当前节点,您vector需要对其进行索引。

于 2013-06-19T02:31:17.227 回答