通过参考C ++传递向量

Sve*_*tsi -1 c++ reference vector

我不知道为什么这行不通?我需要传递矢量引用,以便可以从外部函数对其进行操作。

互联网上对此有几个问题,但我听不懂答复吗?

下面的代码:

#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");


}
Run Code Online (Sandbox Code Playgroud)

Sha*_*het 5

首先,你需要学习引用和指针,然后之间的差异之间的差异pass-by-referencepass-by-pointer

形式的函数原型:

void example(int *);  //This is pass-by-pointer
Run Code Online (Sandbox Code Playgroud)

需要一个类型的函数调用:

int a;         //The variable a
example(&a);   //Passing the address of the variable
Run Code Online (Sandbox Code Playgroud)

而形式的原型:

void example(int &);  //This is pass-by-reference
Run Code Online (Sandbox Code Playgroud)

需要一个类型的函数调用:

int a;       //The variable a
example(a);  
Run Code Online (Sandbox Code Playgroud)

使用相同的逻辑,如果您希望通过引用传递矢量,请使用以下命令:

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

int main()
{
vector<string> v;
funct(v);            //Function call
}
Run Code Online (Sandbox Code Playgroud)

编辑:指向有关指针和引用的基本说明的链接:

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