通过参考C 传递向量
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
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 如何将向量分配给参考变量?
- 使用指针向量到参考向量是非法的吗?
- 如何通过参考传递向量的静态向量
- 如何通过参考构建向量的子句法
- Lambdas的C 向量 - 未定义的参考
- 将std ::向量作为指针参考
- 如何在向量内有一对带有参考的对?
- 调用clear()后,向量的元素仍然可以参考
- 替代STD ::向量存储参考而不是对象的副本
- 传递向量作为参考的正确方法是什么
- 通过参考C 传递向量
- 明确给出该数字时,我应该参考std ::向量大小
- 初始化向量通过参考
- C 地图向量参考错误
- 将STD向量作为参考:无匹配函数要呼叫
- 参考对象的向量
- C++ 向量运算符 [] 参考