调用c++;函数的参数是对向量元素的引用 我正在编写一个C++程序来解决迷宫问题(实际上是迷宫求解线跟随器)。为此,我声明了一个全局变量 vector< node > node_container // to contain each node encountered // with its latest info.
现在我用递归来解决这个迷宫调用c++;函数的参数是对向量元素的引用 我正在编写一个C++程序来解决迷宫问题(实际上是迷宫求解线跟随器)。为此,我声明了一个全局变量 vector< node > node_container // to contain each node encountered // with its latest info.,c++,recursion,vector,maze,C++,Recursion,Vector,Maze,现在我用递归来解决这个迷宫 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_no
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]);
}
现在我的问题是,如果我对vector node_容器元素的引用是正确的,即“current_node”(即它变得无效),那么这个问题的解决方法是什么
一种可能的解决方案是通过值传递参数,而不是通过引用传递参数,并在每次修改任何节点对象时更新node_容器
但这真的是一个混乱的方式,我想做它的网络和清洁
我想说的是,我不是一个非常有经验的程序员,所以如果你能详细说明你的答案,会更有帮助。提前谢谢你
我认为在这一点上[在push_back
]之后]参考变量current_node
变得无效,因为vector
刚刚被重新分配。我说得对吗
是的,你说得对。<代码>向量< /代码>可能或不可重新分配,但由于存在可能性,应考虑先前引用无效。
这个问题的解决方法是什么
如果预先分配了足够的元素,或者使用普通的C数组而不是向量,那么引用将保持有效。您必须确保容量足以在最坏情况下运行,而无需重新分配
如果总是按顺序访问元素,另一种解决方案可能是使用链表,因为向链表中添加元素不会更改对其现有元素的引用。当调整
向量的大小时,引用可能会无效
与其将引用传递给节点本身,不如将向量
索引传递给当前节点
void node_action(int current_node)
{
//...
node_action(node_container.size()-1);
}
//...
node_action(0);
然后,要访问当前节点,您可以索引到vector
来执行此操作。感谢您伟大的回答@jxh…我也有类似的想法,只是我想传递一个节点副本,只是为了提取其节点号,并在节点容器[node\u no]上执行所有操作…我是一个多么大的转储!!!感谢您的回答@dasblinkenlight。。。我刚刚学到了一个关于列表的新东西。。。
void node_action(int current_node)
{
//...
node_action(node_container.size()-1);
}
//...
node_action(0);