'Why and when to pass vector by reference? [duplicate]

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



Solution 1:[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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1