What's the difference between these ranged loops?

What's the difference between these ranged for loops and when is one used over the other and potential advantages?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
   std::vector<int> v = {0, 1, 2, 3, 4, 5};
 
    for (const int& i : v) // access by const reference
        std::cout << i << ' ';
 
    for (auto i : v) // access by value, the type of i is int
        std::cout << i << ' ';
 
    for (auto&& i : v) // access by forwarding reference, the type of i is int&
        std::cout << i << ' ';
 
    const auto& cv = v;
 
    for (auto&& i : cv) // access by f-d reference, the type of i is const int&
        std::cout << i << ' ';
 
This post covers them, and more, and explains when to use each: https://blog.petrzemek.net/2016/08/17/auto-type-deduction-in-range-based-for-loops/
Thanks a lot repeater!
Topic archived. No new replies allowed.