Consider this Python for
loop using a range
:
for i in range(n-2, -1, -1):
As the loop iterates, i
takes on the values n-2
, n-3
, until 0
.
What is the equivalent code in C++?
This question is copied almost verbatim from another deleted question .
The equivalent code in C++ :
for(int i = n-2 ; i > -1 ; i--) {
...
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.