-2

I have a question that why to pass vector or string by reference. simply why to pass a value by reference? let's take a example :- suppose I want pass a vector in function then I'd write below code:-

void fun(vector<string/int>v){
......
......
}

so sometime it gives correct output but sometime it gives wrong.

but when I use:-

void fun(vector<string/int> & v){
......
......
}

then wrong output turns right so tell me when to use & and why ?

thank u in advance...

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
ramkrushna
  • 17
  • 5

1 Answers1

1

Why and when to pass vector by reference?

You should use a reference when you need indirection, and you don't need a pointer.

You may need indirection if

  • You need to avoid unnecessary copying.
  • You intend to modify the object in-place.
  • You need to observe identity (memory address) of the object.

Because:

  • Passing a value potentially requires copying that may be avoided by using indirection. Copying can be expensive, such as in the case of vectors.
  • Without indirection, you cannot modify the argument in-place.
  • If the parameter is a value, then it isn't the same object as the argument and hence they will have a different identities.
  • References cannot be null, which makes them easier to use than pointers and hence preferable when the nullability isn't needed.
eerorika
  • 232,697
  • 12
  • 197
  • 326