[英]Passing a vector as argument to function
I have a function like this: 我有一个这样的功能:
void Foo(std::vector<bool> Visited, int actual element);
I actually use this function for a BFS in a Graph, but it goes in an infinite loop. 实际上,我将此功能用于Graph中的BFS,但它处于无限循环中。 I suspect it always creates a copy of the Visited vector.
我怀疑它总是创建Visited向量的副本。 How do I make it change the vector, which is declared and initialized somewhere in main?
如何使它更改向量,该向量在main中的某个位置进行了声明和初始化? And am I right with the whole "makes a copy" theory?
我对整个“复制”理论是否正确?
How do I use a pointer to an object, as I think <vector>
is an object? 我认为
<vector>
是对象,如何使用指向对象的指针?
Pass it by reference : 通过引用传递它:
void Foo(std::vector<bool>& Visited, int actual element);
^
Now you can modify the original vector passed to Foo
. 现在,您可以修改传递给
Foo
的原始向量。
And am I right with the whole "makes a copy" theory?
我对整个“复制”理论是否正确?
Yes. 是。 Declaring the parameter with no
&
or *
passes the object by value = as a copy. 声明不带
&
或*
的参数将通过值 =将对象作为副本传递。 The same applies to return types etc. (With the exception of move constructors) 这同样适用于返回类型等。(move构造函数除外)
Use the referenced type 使用引用的类型
void Foo(std::vector<bool> &Visited, int actual element);
Otherwise the function deals with a copy of the original vector. 否则,该函数将处理原始向量的副本。
Here is a dempnstrative program 这是一个演示程序
#include <iostream>
#include <vector>
void f( std::vector<int> &v )
{
v.assign( { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } );
}
int main()
{
std::vector<int> v;
f( v );
for ( int x : v ) std::cout << x << ' ';
std::cout << std::endl;
}
The program output is 程序输出为
0 1 2 3 4 5 6 7 8 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.