what is the purpose of using & while passing string or vector to a function by reference like this
int function(string & x){
return 0;
}
or
int function(vector<int>&x){
return 0;
}
why it shows error while using *.
what is the purpose of using & while passing string or vector to a function by reference like this
int function(string & x){
return 0;
}
or
int function(vector<int>&x){
return 0;
}
why it shows error while using *.
When you pass reference with & ,you pass the actual data rather than passing a copy of data . Change you do in the vector is done on actual vector.
Passing by reference i.e. using the &
means you get access to the actual instance you passed to the function, in your case the vector
or the string
. Changes to the variable inside the function will also reflect outside the scope of your function.
thus,
#include <iostream>
int function(std::string & x) {
x = "Hello Function!";
return 0;
}
int main() {
std::string my_string("Hello World!");
function(my_string); // Pass by reference
std::cout << my_string << std::endl; // Will print "Hello Function"
return 0;
}