将向量作为参数传递给函数

Passing a vector as argument to function

我有这样的功能:

void Foo(std::vector<bool> Visited, int actual element);

我实际上将此函数用于图形中的 BFS,但它进入无限循环。我怀疑它总是创建 Visited 向量的副本。 我如何让它改变在main中某处声明和初始化的向量?我对整个 "makes a copy" 理论是否正确?

如何使用指向对象的指针,因为我认为 <vector> 是一个对象?

通过引用传递:

void Foo(std::vector<bool>& Visited, int actual element); 
                          ^

现在您可以修改传递给 Foo 的原始向量。

And am I right with the whole "makes a copy" theory?

是的。声明没有 &* 的参数通过 value = 作为副本传递对象。这同样适用于 return 类型等(移动构造函数除外)

使用引用类型

void Foo(std::vector<bool> &Visited, int actual element);

否则函数处理原始向量的副本。

这是一个演示程序

#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;
}    

程序输出为

0 1 2 3 4 5 6 7 8 9