调用带有引用vector元素参数的c++函数
calling a c++ function with argument that is a reference to vector element
我正在写一个解决迷宫的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,则引用仍然有效。您必须确保容量足以在最坏的情况下运行,而无需重新分配。
如果总是按顺序访问元素,另一种解决方案可能是使用链表,因为向链表添加元素不会改变对其现有元素的引用。
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- static_assert在宏中,但也可以扩展到可以用作函数参数的东西
- 使用指向成员的指针将成员函数作为参数传递
- 没有名称的C++模板参数
- 如何将enable-if与模板参数和参数包一起使用