Let's say we need to print int
array with size N
in reverse order:
// Wrong, i is unsigned and always >= 0:
for(size_t i = N-1; i >= 0; --i){cout << data[i];}
// Correct, but uses int instead of size_t:
for(int i = N-1; i >= 0; --i){cout << data[i];}
// Correct, but requires additional operation in the loop:
for(size_t i = N; i > 0; --i){cout << data[i-1];}
// Probably the best version, but less readable.
// Is this well-defined behavior?
for(size_t i = N-1; i != (size_t)(-1); --i){cout << data[i];}
Is there better way to do such enumeration using size_t
index and without additional operations in the loop?
Is it valid to assume that (size_t)0 - 1
gives (size_t)(-1)
or this is undefined?
You can move the decrement to "after" the condition.
for(size_t i = N; i > 0;) {
--i;
cout << data[i];
}
It's not as elegant as a forwards loop but it works. We break at 0 so i
never wraps.
since C++14:
for (auto it = std::rbegin(data); it != std::rend(data); ++it) { std::cout << *it; }
Or if you can use boost, you may use boost::adaptors::reversed
and for range.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With