Reputation: 305
I can't figure out why this won't work? I need to pass the vector reference so I can manipulate it from an external function.
There are several questions on this on the internet but I can't understand the replies?
code below:.
#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");
}
Upvotes: 0
Views: 10871
Reputation: 334
Firstly you need to learn the differences between references and pointers and then the difference between pass-by-reference
and pass-by-pointer
.
A function prototype of the form:
void example(int *); //This is pass-by-pointer
expects a function call of the type:
int a; //The variable a
example(&a); //Passing the address of the variable
Whereas, a prototype of the form:
void example(int &); //This is pass-by-reference
expects a function call of the type:
int a; //The variable a
example(a);
Using the same logic, if you wish to pass the vector by reference, use the following:
void funct(vector<string> &vec) //Function declaration and definition
{
//do something
}
int main()
{
vector<string> v;
funct(v); //Function call
}
EDIT: A link to a basic explanation regarding pointers and references:
https://www.dgp.toronto.edu/~patrick/csc418/wi2004/notes/PointersVsRef.pdf
Upvotes: 9