Pass a vector by reference C++

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:

Leave a Comment