Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing vectors by reference

Tags:

If I have a vector of objects in one class which I want to change in another, I would try and pass all the information by reference.

What exactly do I need to pass by reference though? The vector? The objects? Both?

Essentially what I'm asking is: What is the difference between these?

vector&<object> blah; // A reference to a vector of objects?  vector<object&> blah; // A vector of references to objects?  vector&<object&> blah; // A reference to a vector of references to objects??? 

I'm not actually sure how referencing of array like containers work. Are these legal?

like image 970
Dollarslice Avatar asked Nov 01 '11 12:11

Dollarslice


People also ask

Can you pass a vector by reference?

When we pass an array to a function, a pointer is actually passed. However, to pass a vector there are two ways to do so: Pass By value. Pass By Reference.

What are the advantages of passing a vector by reference?

Pass by reference allows us to pass arguments to a function without making copies of those arguments each time the function is called.

How do you pass by reference?

Pass by reference (also called pass by address) means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function so that a copy of the address of the actual parameter is made in memory, i.e. the caller and the callee use the same variable for the parameter.


2 Answers

vector&<object> is a syntax error. vector<object&> is invalid, because a vector's value type must be assignable. vector&<object&> blah is a syntax error.

A reference to a vector is vector<T>&.

like image 73
Cat Plus Plus Avatar answered Oct 07 '22 00:10

Cat Plus Plus


You cannot have a vector of references. Vector elements must be copyable and assignable, which references are not. So only the first option is actually an option, but it's spelled std::vector<Object> &.

Note that v[1] already returns a reference to the second element, so you can happily pass individual elements by reference.

It is possible to have a vector of reference-wrappers a la std::ref, but if you don't know what that is, you probably shouldn't be using it at this point.

like image 39
Kerrek SB Avatar answered Oct 06 '22 23:10

Kerrek SB