Range based for loop

Doesn't mean for (const auto& x : v) { /* do something with the value of x */ } this for (auto x : v) { /* do something with the value of x */ } supposing v is an std::vector?

Which one would you use, why?



Last edited on
efficiency.
the first one does not make a copy to populate X, it uses the value directly.
the second one copies into X. For large objects, this is a performance killer, same reason you use reference parameters to a function when calling it with a fat object.


Got it, thank you very much.
Something else to note: the use of const in the first loop.

To let the compiler flag any unintended alteration of the elements.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>

int main()
{
   std::vector<int> vec { 1, 2, 3, 4, 5, 6, 7 };

   for (const auto& itr : vec)
   {
      itr++; // error, expression must be a modifiable lvalue
   }
}

Even if you didn't use & in the ranged based for loop, const still won't let any changes happen in the loop body.
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <vector>

int main()
{
   std::vector<int> vec { 1, 2, 3, 4, 5, 6, 7 };

   for (const auto itr : vec)
   {
      itr++; // error, expression must be a modifiable lvalue
   }
}
^^^
that is a whole new discussion, but the & means that changes (if you left the const off) would change the data IN THE VECTOR. (this is about 50-50 on whether you wanted to do that or not, often you do, and often you don't!).
you need to get comfortable with const keyword and references as you should use both frequently in c++.
Last edited on
Topic archived. No new replies allowed.