Range based for loop

Dec 23, 2021 at 5:48am
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 Dec 23, 2021 at 5:49am
Dec 23, 2021 at 5:55am
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.


Dec 23, 2021 at 7:17am
Got it, thank you very much.
Dec 23, 2021 at 3:58pm
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
   }
}
Dec 23, 2021 at 4:12pm
^^^
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 Dec 23, 2021 at 4:13pm
Topic archived. No new replies allowed.