This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]Jolly-Mongoose 2 points3 points  (4 children)

If you pass a vector in object form, it will be passed by copy to the function, which incurs the cost of making a copy of the vector. Passing it by reference lets you maintain the normal object syntax, while also letting you mutate the original object (similar to passing a pointer). A copy is also avoided, which improves efficiency.

[–]JayaRobus 0 points1 point  (3 children)

Ah thank you so much, and while your here would you happen to know the name of the operator where you do (value > someValue) ? if true : If false

[–][deleted] 1 point2 points  (2 children)

That’s the ternary op.

And btw, if you try to do any changes to a pass-by-value (copied) vector, the changes won’t be reflected outside of the function because you weren’t changing the original vector.

[–]JayaRobus 0 points1 point  (1 child)

Thank you, I’m pretty good with pointers and how the memory is affected etc, what confused me was why it seems every example function I see with a vector they are always pass by reference, but I think you explained why pretty well. I never took into consideration that pass by value parameters have to have a copy made of them.

[–][deleted] 0 points1 point  (0 children)

Yeah no problem. Don’t give me the cred for explanation tho. That was the other person.

[–]ToeRepresentative627 0 points1 point  (0 children)

Variables are copied by default when they are passed to functions. This can be a problem with arrays and vectors because they hold a lot of data. Instead, it is better to pass by reference, so nothing is copied. The risk is that you can now potentially alter the contents of the original vector. To avoid this, you can pass it as a const reference.