I'm coding in C++. If I have some function void foo(vector<int> test)
and I call it in my program, will the vector be passed by value or reference? I'm unsure because I know vectors and arrays are similar and that a function like void bar(int test[])
would pass test in by reference (pointer?) instead of by value. My guess is that I would need to pass the vector by pointer/reference explicitly if I wanted to avoid passing by value but I'm not sure.
A vector
is functionally same as an array. But, to the language vector
is a type, and int
is also a type. To a function argument, an array of any type (including vector[]
) is treated as pointer. A vector<int>
is not same as int[]
(to the compiler). vector<int>
is non-array, non-reference, and non-pointer - it is being passed by value, and hence it will call copy-constructor.
So, you must use vector<int>&
(preferably with const
, if function isn't modifying it) to pass it as a reference.
void foo(vector<int> test)
vector would be passed by value in this.
You have more ways to pass vectors depending on the context:-
1) Pass by reference:- This will let function foo change your contents of the vector. More efficient than pass by value as copying of vector is avoided.
2) Pass by const-reference:- This is efficient as well as reliable when you don't want function to change the contents of the vector.
when we pass vector by value in a function as an argument,it simply creates the copy of vector and no any effect happens on the vector which is defined in main function when we call that particular function. while when we pass vector by reference whatever is written in that particular function, every action will going to perform on the vector which is defined in main or other function when we call that particular function.
Source: Stackoverflow.com