Where does rend point to?
The result of rbegin
points to the same as end
(one past the end), and the result of rend
to the same as begin
(the first item). When a reverse iterator is dereferenced, it returns a reference to the previous item in the range.
There is a difference between what a reverse_iterator
points to logically and what its contained iterator points to. Logically, rbegin
yields an iterator that points to the last element of the sequence and rend
yields an iterator that points to one element before the start. But this is usually implemented with a base iterator which points to the next location after the location the reverse iterator is pointing to. Something like this:
template<class Iter>
class reverse_iter
{
Iter base;
public:
explicit reverse_iter(Iter it) : base(it) {}
reference operator*() const {
Iter tmp = base;
--tmp;
return *tmp;
}
reverse_iter& operator++() {--base; return *this;}
};
So, if you initialize such a reverse_iter<>
object with container.end()
, the base iterator points one past the end, but dereferencing the reverse iterator will give you the last element. No harm done.
Because you're not permitted to dereference an iterator that points outside the container, it doesn't actually matter what rend()
"points" to. It doesn't have to be a legal pointer value, it can be any value that has a particular meaning to the container/iterator type.