25

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dollarslice
  • 9,917
  • 22
  • 59
  • 87

3 Answers3

55

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • 1
    ok so you just store a reference to a vector... and when accessing an element of said vector by index you're actually accessing the original object? – Dollarslice Nov 01 '11 at 16:08
4

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
2

Another option is to pass around iterators instead of containers. This is the approach the standard library takes in <algorithm>. They are slightly more verbose at the calling site, but they have the advantage that they work for parts of a collection as well as complete collections and decouples the algorithm from the container.

Lastly, of course, it's worth while checking you know your algorithms as there may already be one that does what you want.

L. F.
  • 19,445
  • 8
  • 48
  • 82
jk.
  • 13,817
  • 5
  • 37
  • 50