-1

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 *.

2 Answers2

2

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.

Harsh Chaturvedi
  • 679
  • 6
  • 13
0

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;
}
Jan Gabriel
  • 1,066
  • 6
  • 15