size_t going down from uplimit to 0?

to go through an array from 0 is easy

for(size_t i=0; i<size; i++)

but when going starting from high limit, things changed

for(size_t i=size-1; i>=0; i--)

this will cause i go below zero and then being converted to a large positive value and the for loop never ending

I know this is a simple question, but how do you guys do this? Thanks.
Last edited on
I'd just use a signed type like int... rather than size_t.
In C++14 you can use std::rbegin and std::rend
http://en.cppreference.com/w/cpp/iterator/rbegin
http://en.cppreference.com/w/cpp/iterator/rend
Unfortunately I can't give e.g. an ideone example because of the lack of support for C++14 :(
Last edited on
non-member rbegin/rend are not all that complicated to stick into your own library (if you don't have them already), or you can just construct reverse iterators directly in C++98:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <iterator>
int main()
{
    const int N = 5;
    int a[N] = {1,2,3,4,5};

    typedef std::reverse_iterator<int*> iter_t;

    for(iter_t i = iter_t(a+N); i != iter_t(a); ++i)
        std::cout << *i << ' ';
}


PS: if you want indexing, for(std::size_t i = N-1; i != (std::size_t) -1; --i) is safe because of how unsigned integer arithmetic is defined.
Last edited on
Topic archived. No new replies allowed.