forward and reverse for loops with C++ containers

(I'm including SSCCE [ http://www.sscce.org/ ]code snippets so those not familiar with the subject can follow along, the regulars here will implicitly understand without the verbiage)

There are 3 basic ways to "walk through" a container. I'll use a std::vector to illustrate

1. The old-school C/C++ for loop:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>

int main()
{
   std::vector v { 1, 2, 3, 4, 5 };

   for (auto itr { 0 }; itr < v.size(); ++itr)
   {
      std::cout << v[itr] << ' ';
   }
   std::cout << '\n';
}

2. Using iterators:
1
2
3
4
5
   for (auto itr { v.cbegin() }; itr != v.cend(); ++itr)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';

3. The C++11 range-based for loop:
1
2
3
4
5
   for (const auto& itr : v)
   {
      std::cout << itr << ' ';
   }
   std::cout << '\n';

Reversing the first two for loops is easy:
1
2
3
4
5
6
7
8
9
10
11
   for (int itr = v.size() - 1; itr >= 0; --itr)
   {
      std::cout << v[itr] << ' ';
   }
   std::cout << '\n';

   for (auto itr { v.crbegin() }; itr != v.crend(); ++itr)
   {
      std::cout << *itr << ' ';
   }
   std::cout << '\n';

Yet there is no way to do a reverse range-based for loop. Well, there wasn't until C++20 introduced the <ranges> library:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <vector>
#include <ranges>

int main()
{
   std::vector v { 1, 2, 3, 4, 5 };

   // https://www.fluentcpp.com/2020/02/11/reverse-for-loops-in-cpp/
   for (const auto& itr : v | std::views::reverse)
   {
      std::cout << itr << ' ';
   }
   std::cout << '\n';
}

Not as elegant as the other for loops, but it does work.
FYI, Visual Studio 2019, build 16.11.2 requires the C++ language standard to be set to /std:c++latest to compile. Set the language standard to C++20 and VS spits out the following errors:
The contents of <ranges> are available only in c++latest mode with concepts support;
see https://github.com/microsoft/STL/issues/1814 for details.

While searching the bowels of the interwebs to find out the possibilities of a reverse range-based for loop I found at stackoverflow this interesting regular reverse for loop variation I thought was a bit ingenious:
1
2
3
4
5
   for (auto itr = v.size(); itr --> 0;)
   {
      std::cout << v[itr] << ' ';
   }
   std::cout << '\n';

Meta-search: https://duckduckgo.com/?q=c%2B%2B+array+reverse+for+loop&t=ffsb&ia=web
stackoverflow:
https://stackoverflow.com/questions/275994/whats-the-best-way-to-do-a-backwards-loop-in-c-c-c
Topic archived. No new replies allowed.