通过参考C 传递向量

Pass a vector by reference C++

本文关键字:向量 参考      更新时间:2023-10-16

我不知道为什么这不起作用?我需要传递向量参考,以便我可以从外部功能中操纵它。

互联网上有几个问题,但我不明白答复?

代码下面:。

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

}

首先,您需要学习引用和指针之间的差异,然后学习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