0

What is the difference between

void printVector ( std::vector<int> & v ) {

for ( auto &i : v )
    std::cout << i << std::endl;
}

void printVector ( std::vector<int> & v ) {

for ( auto i : v )
    std::cout << i << std::endl;
}

I'm curious about the & before i:

  • Does it have to be there ( even thought it works the same in both cases ) ?
  • What does it do?
paxie
  • 137
  • 1
  • 2
  • 9

1 Answers1

2

The first version gets a reference to the element of the vector, thus allowing you to modify the element in the vector.

The second version gets the element "by value", which involves a copy and does not allow you to modify the value.

It is pretty much the same as with function parameters and might make a difference when working with const qualifiers (might require the second version) or large objects which do not allow copies (require first version) or where copies are expensive (prefer first version).

In your case it doesn't make much of a difference, since you don't modify i and a copy of an int is cheap. The compiler might even optimize the copy away.

Anedar
  • 4,235
  • 1
  • 23
  • 41