How can I convert this python for-loop using a range into C++?

While the classic for(;;) loop can be used for any iteration that you can imagine, your particular loop can be written more readably like this:

namespace sv = std::views;

for (int i : sv::iota(0, n-1) | sv::reverse)
{
  // ...
}

Here’s a demo.

For completeness, here’s what a classic for(;;) loop would look like:

for (int i = n-2; i > -1; --i)
{
  // ...
}

In my opinion, this is more cognitive effort, precisely because I have to run the iteration in my head by reading the syntax. I find the first version reads more naturally.

Browse More Popular Posts

Leave a Comment