[英]Pass a vector by reference 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");
}
首先,您需要了解引用和指针之间的区别,然后了解pass-by-reference
和pass-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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.