Victor Brunell
Victor Brunell

Reputation: 6438

Why use rbegin() instead of end() - 1?

I'm wondering what the benefits of using rbegin() rather than end() - 1 are for STL containers.

For example, why would you use something like:

vector<int> v;
v.push_back(999);
vector<int>::reverse_iterator r = v.rbegin();
vector<int>::iterator i = r.base();

Rather than:

vector<int> v;
v.push_back(999);
auto r = v.end() - 1;

Upvotes: 21

Views: 21534

Answers (2)

Paolo M
Paolo M

Reputation: 12777

rbegin() return an iterator with a reverse operator++; that is, with a reverse_iterator you can iterate through a container going backward.

Example:

#include <vector>
#include <iostream>

int main()
{
    std::vector<int> v{0,1,2,3,4};
    for( auto i = v.rbegin(); i != v.rend(); ++i )
        std::cout << *i << '\n';
}

Furthermore, some standard containers like std::forward_list, return forward iterators, so you wouldn't be able to do l.end()-1.

Finally, if you have to pass your iterator to some algorithm like std::for_each that presuppose the use of the operator++, you are forced to use a reverse_iterator.

Upvotes: 34

Mark Ransom
Mark Ransom

Reputation: 308452

If the container is empty, end() - 1 will not be defined.

Upvotes: 20

Related Questions