簡體   English   中英

將向量作為參數傳遞給函數

[英]Passing a vector as argument to function

我有一個這樣的功能:

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

實際上,我將此功能用於Graph中的BFS,但它處於無限循環中。 我懷疑它總是創建Visited向量的副本。 如何使它更改向量,該向量在main中的某個位置進行了聲明和初始化? 我對整個“復制”理論是否正確?

我認為<vector>是對象,如何使用指向對象的指針?

通過引用傳遞它:

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

現在,您可以修改傳遞給Foo的原始向量。

我對整個“復制”理論是否正確?

是。 聲明不帶&*的參數將通過 =將對象作為副本傳遞。 這同樣適用於返回類型等。(move構造函數除外)

使用引用的類型

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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM