When i use a string as a parameter to a method the changes to the string within the function are not not reflected back in the calling function. Simple reason Passing by value.
But when a use a vector the changes to the vector are reflected back in the calling function. So my question here is does passing vectors is like call by reference where we are sending the address in memory rather than the variable hence any changes within the functions re reflected back in calling function
------------------------Update--------------------------------
so vectors have to be passed by reference only? i can't do it normally?
of course you can pass them normally (that is pass them by value). but when you pass objects by value what happens is that a new object is created and then the object you pass is copied to the new object. this, for standard types (char, int, float etc) is ok, because standard types are small in size (char is one byte, short is 2, int is 2 or 4, long is 4 etc...). a vector however is not that small. Try doing this:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v;
cout << sizeof(v) << endl;
system("pause");
return 0;
}
in my pc I get 12 as an output. that's 12 bytes. so instead of passing by value, I pass it by reference which has a cost of 4 bytes (the size of the variable holding the address of my vector)