In C++, std::list::rbegin() returns a reverse iterator that points at the last element of a std::list. When you use ++ on it, it moves toward the first element.
That makes it easy to loop through a list backwards without changing the list. Pair it with rend(). Include <list> to use it.
This is a member of std::list<T>, a doubly linked list. Every element lives in its own node with a link to the previous and the next node, so a list can insert and erase anywhere quickly once you hold an iterator. It has no access by index, so l[i] does not exist.
Syntax
Call rbegin with empty brackets and use it with rend().
C++
for (auto it = l.rbegin(); it != l.rend(); ++it) {
// visits the last element first
}
int last = *l.rbegin(); // same as l.back()
Call
What it does
l.rbegin()
Returns a reverse_iterator to the last element. On an empty list it equals rend().
With reverse iterators, ++ goes backwards through the list. You do not write -- in the loop.
*l.rbegin() is a reference to the last element, so it can be assigned to.
*l.rbegin() = 99 changes 30 to 99 inside the list.
back() and *l.rbegin() reach the same node, so both lines print 99.
Example 3 — rbegin() and base() to Erase
Find the last2 by searching from the back, and then erase it with a normal iterator.
C++
#include <algorithm>
#include <iostream>
#include <iterator>
#include <list>
int main() {
std::list<int> l = {1, 2, 3, 2, 4};
auto r = std::find(l.rbegin(), l.rend(), 2);
l.erase(std::next(r).base());
for (int n : l) {
std::cout << n << ' ';
}
std::cout << '\n';
return 0;
}
Output
1 2 3 4
How It Works
std::find() with reverse iterators searches from the back, so r shows the 2 that is nearest to the back, the one at position four.
r.base() would point one element after it, at 4. Taking std::next(r).base() gives an iterator to the element that r shows.
erase() removes that node, so only the last 2 is gone and the output is 1 2 3 4.
Frequently Asked Questions
A reverse iterator that points at the last element of the list. Using ++ on it moves toward the first element.
Use for (auto it = l.rbegin(); it != l.rend(); ++it). Each ++ moves one element closer to the front.
No. The list is not changed. Only the direction of the walk is reversed. To really reverse the list, use reverse().
It returns the matching normal iterator, which points one element after the element that the reverse iterator shows. Use std::next(r).base() to get an iterator to the same element.
back() returns a reference to the last element. rbegin() returns a reverse iterator to it, which you can move through the list.