dimanche 30 novembre 2014

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 I don't like this:
size_t counter = N-1;
for(size_t i = 0; i < N; ++i){cout << data[counter--];}


Is there elegant way to do such enumeration without additional variable and using size_t index?





Aucun commentaire:

Enregistrer un commentaire