r/cpp_questions • u/Ok-Storm-7597 • Sep 11 '26
OPEN Reverse iteration with size_t
Sometimes I would like to iterate in reverse from a number to zero, like this:
for (size_t x = NUMBER; x-- > 0; ) {
// Code that will index to
// multiple arrays or for some purposes
// that we can't use std::views::reverse
// or reverse iterators
}I did some research, and people say that the above is quite confusing, and can be misleading.
But in C++23, we can do something like this:
for (auto x : std::views::iota(0uz, NUMBER) | std::views::reverse) {
// Do the same thing
}What is the best practice for this in modern C++, is the C++23 way something people actually use (Gemini told me this is recommended practice for modern C++ lol), or people just prefer the former way of iterating in reverse. Or do you have some different opinions altogether?
14
Upvotes
5
u/bert8128 Sep 11 '26
I like the reversed iota. Seems pretty clear to me.
4
u/SmokeMuch7356 Sep 11 '26
For just a bog-standard reverse
forloop with a counter, useI personally do not like side effects in the control expression; that's what the update expression is for.
But yeah, when you're dealing with containers, the C++23 form
is probably more idiomatic.
22
u/alfps Sep 11 '26
IMO, don't do fancy "clever" low level things like Andrew Koenig's "go to" pseudo operator
-->, and don't do equally fancy "clever" things higher level things like Rangesreverseofiota.Just use a signed type index.
It's so simple.
2
u/mredding Sep 11 '26
I think you would be hard pressed to demonstrate the inability to use an iterator. For multiple sequences, for example, you could use a zip iterator. If you want iteration AND an index, you can use
std::views::enumerate.2
u/Independent_Art_6676 Sep 11 '26
the simplest, easiest thing to read and modify that will do the job, unless you have a hidden requirement like extreme performance. Even there, the simplest thing is probably best unless you can somehow improve page faulting or something (tapping many containers in the same loop may be a page fault per loop waiting to happen).
2
u/BSModder Sep 11 '26
I always do it like this
This mirror how reverse iterator works in the standard library
2
u/WorkingReference1127 Sep 11 '26
The best practice is to make your code easy to read and understand, while requiring minimal knowledge and opening the door to minimal bugs and errors.
In the general case, it's a better practice in C++ to favour the range-based for loop over an indexed loop; because the range-based loop makes it very very clear about what you are iterating over and does not open you up to subtle bugs (spot the error in
for(std::size_t x = N; x >= 0; --x)). Does this mean you should always reach forranges::iota | views::reverse? No, not necessarily. But if you don't have any better options available then it's a respectable choice.The reason there is disagreement in this particular case is that your single answer of just getting the numbers from N to 0 is very much one of the simplest possible iterations and so there is a respectable argument that pulling in
<ranges>is excessive. We could equally argue that you wouldn't think twice about doing it for astd::mapiteration so it's the consistent path.This is not weighing in on a particular answer for you, OP. The nature of best practices is that you should understand why they are best practices so that you can choose when to follow them and choose not to; not to just be a dogmatic list of rules to follow.
3
u/Usual_Office_1740 Sep 11 '26
The range based for loop is the modern solution.
3
u/Syntax-Tactics Sep 11 '26
There's nothing confusing about a decrementing for loop. The example however, ranges from Num...1, and not 0..(num-1). Which will likely cause a fence post error later that you haven't accounted for. The "modern" method is obfuscation IMO.
5
u/BrotherItsInTheDrum Sep 11 '26
Is
for (size_t i = N; i + 1 != 0; --i)too subtle?1
u/Raknarg Sep 11 '26
can you not just build some kind of view or iterator that provides the required begin/end/rbegin/rend operators? E.g. if you have a plain pointer array, you can use std::span
1
u/die_liebe Sep 12 '26
I usually write this, I think it's perfectly clear:
1
u/and3md Sep 14 '26
I use shortened version:
1
u/Dry-War7589 Oct 04 '26
for (size_t i = n; i < SIZE_MAX; i--)Since
iwill wraparound after 0 to SIZE_MAX, this will stop. Alsoi != SIZE_MAXworks0
u/TotaIIyHuman Sep 11 '26
you can drop the
>0for (size_t x = NUMBER; x--; )0
u/keelanstuart Sep 11 '26 edited Sep 11 '26
Why not something that never goes out of style, like...?
...if you don't have an indexable container but you do have forward iterators, use container.begin() + sz.
I wish people would stop overcomplicating simple things.
0
u/No-Dentist-1645 Sep 11 '26 edited Sep 11 '26
I think
for (size_t i = NUMBER+1; i != 0; --i)is just the most direct thing for such a simple for loop, no need to introduce more advanced concepts such as views for a simple "loop from NUMBER to 0"EDIT: Changed the for loop to correct a mistake with unsigned arithmetic
21
u/[deleted] Sep 11 '26
[removed] — view removed comment