0
#include <bits/stdc++.h>

int main () {
  std::string foo = "string_1";
  std::string bar = "string_2";
  std::vector<std::string> myvector;

  myvector.push_back (foo);
  myvector.push_back (std::move(bar));
  for (std::string x:myvector) 
    std::cout << x << '\n' ;
}

How's that code is diffrent when I exchange

  for (std::string x:myvector)

for?

  for (std::string& x:myvector)

I'm guessing there are a lot of places when I could find that, but I don't know what's the name of this measure, so I don't know what I should search for. Link to explanation will be enough if it's it's easier for you.
EDIT:
What's the diffrence between:

for(auto x:my_vector)

for(auto& x:my_vector)

for(auto&& x:my_vector)
miszcz2137
  • 894
  • 6
  • 18
  • It's called "reference". – Kerrek SB Jul 18 '17 at 17:23
  • 1
    Possible duplicate of [C++ copy constructor syntax: Is ampersand reference to r/l values?](https://stackoverflow.com/questions/33290801/c-copy-constructor-syntax-is-ampersand-reference-to-r-l-values) – R Sahu Jul 18 '17 at 17:44
  • Don't include , it's a non standard header, not meant for inclusion. –  Jul 18 '17 at 19:14
  • you advise diffrent header similar to bist/stdc++.h or include everything separately? – miszcz2137 Jul 18 '17 at 19:24

1 Answers1

3

What does '&' after class name mean?

The ampersand is part of the type in the declaration and signifies that the type is a reference. Reference is a form of indirection, similar to a pointer.

What's the diffrence between:

for(auto x:my_vector)

The loop variable is a non-reference. It will contain a copy of the object in the container.

for(auto& x:my_vector)

The loop variable is an lvalue reference. Since the variable references the objects in the container, they can be modified through that reference. This also avoids copying the objects, which may be advantageous if the copy is expensive.

for(auto&& x:my_vector)

The loop variable is a universal reference. This means that it will be either an lvalue or rvalue reference, depending on the type returned when the iterator of the container is dereferenced. As far as I know, there are only a few obscure cases where this is useful. You'll probably never need it.

eerorika
  • 232,697
  • 12
  • 197
  • 326