2017-01-01 63 views
-2

我想不通爲什麼這不起作用? 我需要傳遞向量引用,所以我可以從外部函數中操作它。通過引用傳遞一個向量C++

在互聯網上有幾個關於這個問題,但我不明白的答覆?

代碼如下:

#include <iostream> 
#include <vector> 
#include <string> 


using namespace std; 

string funct(vector<string> *vec) 
{ 
    cout << vec[1] << endl; 

} 



int main() 
{ 

vector<string> v; 
v.push_back("one"); 
v.push_back("two"); 
v.push_back("three"); 


} 
+4

'vector * vec'表示通過指針傳遞,如果您想通過引用傳遞,則將其更改爲'vector &vec'。 – songyuanyao

+2

我沒有看到你傳遞任何向量。通過參考或價值。 – StoryTeller

+2

好問題。在網絡上很差的地址。下面的答案很好,但是在將向量作爲函數參數傳遞時,它不會處理指針。 – domonica

回答

3

首先,你需要學習引用和指針,然後pass-by-referencepass-by-pointer之間的差異之間的差異。

形式的函數原型:

void example(int *); //This is pass-by-pointer 

預計的類型的一個函數調用:

int a;   //The variable a 
example(&a); //Passing the address of the variable 

然而,原型的形式爲:

void example(int &); //This is pass-by-reference 

期望一個功能呼叫類型:

int a;  //The variable a 
example(a); 

使用相同的邏輯,如果你想通過引用傳遞的載體,使用以下命令:

void funct(vector<string> &vec) //Function declaration and definition 
{ 
//do something 
} 

int main() 
{ 
vector<string> v; 
funct(v);   //Function call 
} 

編輯:一個鏈接到一個基本解釋關於指針和引用:

https://www.dgp.toronto.edu/~patrick/csc418/wi2004/notes/PointersVsRef.pdf