When we pass an array to a function, a pointer is actually passed.
However, to pass a vector there are two ways to do so:
- Pass By value
- Pass By Reference
When a vector is passed to a function, a copy of the vector is created. This new copy of the vector is then used in the function and thus, any changes made to the vector in the function do not affect the original vector.
For example, we can see below the program, changes made inside the function are not reflected outside because the function has a copy.
Example(Pass By Value):
CPP
#include <bits/stdc++.h>
using namespace std;
void func(vector< int > vect) { vect.push_back(30); }
int main()
{
vector< int > vect;
vect.push_back(10);
vect.push_back(20);
func(vect);
for ( int i = 0; i < vect.size(); i++)
cout << vect[i] << " " ;
return 0;
}
|
Passing by value keeps the original vector unchanged and doesn’t modify the original values of the vector. However, the above style of passing might also take a lot of time in cases of large vectors. So, it is a good idea to pass by reference.
Example(Pass By Reference):
CPP
#include <bits/stdc++.h>
using namespace std;
void func(vector< int >& vect) { vect.push_back(30); }
int main()
{
vector< int > vect;
vect.push_back(10);
vect.push_back(20);
func(vect);
for ( int i = 0; i < vect.size(); i++)
cout << vect[i] << " " ;
return 0;
}
|
Passing by reference saves a lot of time and makes the implementation of the code faster.
Note: If we do not want a function to modify a vector, we can pass it as a const reference also.
CPP
#include<bits/stdc++.h>
using namespace std;
void func( const vector< int > &vect)
{
for ( int i = 0; i < vect.size(); i++)
cout << vect[i] << " " ;
}
int main()
{
vector< int > vect;
vect.push_back(10);
vect.push_back(20);
func(vect);
return 0;
}
|
This article is contributed by Kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.