In C++, std::map::rbegin() returns a reverse iterator that starts at the last pair of the map. The last pair is the one with the biggest key.
With a reverse iterator, ++ moves toward smaller keys. That lets you walk a map backwards, or get its biggest key quickly. Include <map> to use it.
This is a member of std::map<Key, T>, a sorted container of key and value pairs. Each key is unique and the pairs are always kept in key order, so a map can find, insert, and erase a key in logarithmic time. Read a value with at() or find(). The m[key] operator also works, but it adds a default value when the key is missing.
Syntax
Call rbegin with empty brackets. Stop at rend().
C++
auto it = m.rbegin(); // biggest key
for (auto p = m.rbegin(); p != m.rend(); ++p) {
// from biggest key to smallest
}
Call
What it does
m.rbegin()
Returns a reverse_iterator to the last pair. On a const map it returns a const_reverse_iterator.
A reverse iterator r has a method r.base() that gives the normal iterator one position after it. So std::next(r).base() is the normal iterator for the same pair, which is useful for erase().
rbegin() starts on the pair with key 3, the last one in the sorted map.
For a reverse iterator ++it steps toward the front, so the keys come out 3, 2, 1.
The loop ends when it reaches rend(), the position before the first pair. The map itself is not changed.
Example 3 — rbegin() and erase()
Remove the pair with the biggest key by turning the reverse iterator into a normal one.
C++
#include <iostream>
#include <iterator>
#include <map>
int main() {
std::map<int, char> m = {{1, 'a'}, {2, 'b'}, {3, 'c'}};
if (!m.empty()) {
m.erase(std::next(m.rbegin()).base()); // remove the pair for key 3
}
for (const auto& kv : m) {
std::cout << kv.first << kv.second << ' ';
}
std::cout << '\n';
return 0;
}
Output
1a 2b
How It Works
erase() only accepts normal iterators, so m.erase(m.rbegin()) would not compile.
base() gives the normal iterator one position after a reverse iterator, so std::next(m.rbegin()).base() is the normal iterator for the pair at rbegin(), the one with key 3.
That pair is erased, and the loop prints what remains: 1a 2b.
Frequently Asked Questions
A reverse iterator that points to the last pair of the map, which has the biggest key.
Use m.rbegin()->first, after checking that the map is not empty. Or use std::prev(m.end()).
Use m.erase(std::prev(m.end())), or convert the reverse iterator with std::next(m.rbegin()).base().
It moves toward smaller keys, so the loop goes from the biggest key to the smallest.
rbegin() on a non-const map lets you change values. crbegin() always returns a read-only reverse iterator.