Search code examples
c++vectoriterator

Iterating C++ vector from the end to the beginning


Is it possible to iterate a vector from the end to the beginning?

for (vector<my_class>::iterator i = my_vector.end();
        i != my_vector.begin(); /* ?! */ ) {
}

Or is that only possible with something like that:

for (int i = my_vector.size() - 1; i >= 0; --i) {
}

Solution

  • One way is:

    for (vector<my_class>::reverse_iterator riter = my_vector.rbegin();
         riter != my_vector.rend(); ++riter) 
    { 
        // do stuff
    } 
    

    rbegin()/rend() were especially designed for that purpose. (And yes, incrementing a reverse_iterator moves it backward.)

    Now, in theory, your method (using begin()/end() & --i) would work, std::vector's iterator being bidirectional, but remember, end() isn't the last element — it's one beyond the last element, so you'd have to decrement first, and you are done when you reach begin() — but you still have to do your processing.

    vector<my_class>::iterator iter = my_vector.end();
    while (iter != my_vector.begin())
    {
         --iter;
        /*do stuff */
    }