What is rbegin and rend in C++: Explanation and Example
rbegin and rend are member functions in C++ containers that return reverse iterators. rbegin points to the last element, and rend points just before the first element, allowing you to iterate over a container backwards.How It Works
Imagine you have a row of books on a shelf, and you want to look at them starting from the last book to the first. In C++, rbegin gives you a pointer to the last book, and rend marks the position just before the first book. This lets you walk backwards through the books easily.
Normally, iterators go from the start to the end of a container. Reverse iterators do the opposite: they start at the end and move to the beginning. Using rbegin and rend, you can loop through elements in reverse order without changing the container itself.
Example
This example shows how to print the elements of a vector in reverse order using rbegin and rend.
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {10, 20, 30, 40, 50}; // Iterate backwards using rbegin and rend for (auto it = numbers.rbegin(); it != numbers.rend(); ++it) { std::cout << *it << " "; } std::cout << std::endl; return 0; }
When to Use
Use rbegin and rend when you need to process elements from the end to the start. For example, if you want to reverse-print a list, or if an algorithm requires backward traversal, these functions make it simple and safe.
They are especially useful with containers like std::vector, std::deque, and std::list where reverse iteration is common. Instead of manually calculating indexes or reversing the container, you can just use these reverse iterators.
Key Points
rbegin()returns a reverse iterator to the last element.rend()returns a reverse iterator just before the first element.- They allow safe and easy backward traversal of containers.
- Commonly used with standard containers like vectors, lists, and deques.
- Reverse iterators move from end to start, opposite of normal iterators.
Key Takeaways
rbegin and rend provide reverse iterators for backward traversal.