Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 219
Victor Brunell Avatar asked Aug 25 '15 15:08

Victor Brunell


People also ask

Is Rbegin same as end?

The onl difference between begin(), end() and rbegin(), rend() is that: begin() and end() will return bidirectional iterator. rbegin() and rend() will return reverse iterator.

What is use of Rbegin in C++?

The rbegin() is a function in C++ STL. It returns a reverse iterator which points to the last element of the map. The reverse iterator iterates in reverse order and incrementing it means moving towards beginning of map.

What is Rbegin and rend in CPP?

vector rbegin() and rend() function in C++ STL Return value: The function returns a reverse iterator pointing to the last element in the container.

What does end () point to?

end() points to somewhere past the end of the container. By convention, sequences in C++ are of the form [begin, end) , that is, the end is not part of the sequence. For arrays and vectors, end() points to the index equal to the size of the array (which is outside the array or vector).


1 Answers

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.

like image 66
Paolo M Avatar answered Sep 23 '22 01:09

Paolo M