Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerating array in reverse order using size_t index

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?

like image 465
Alex F Avatar asked Dec 01 '14 08:12

Alex F


2 Answers

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.

like image 193
Radiodef Avatar answered Nov 09 '22 23:11

Radiodef


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.

like image 20
Jarod42 Avatar answered Nov 09 '22 23:11

Jarod42