C++ std::list::rbegin
The std::list::rbegin
function returns a reverse iterator pointing to the last element of a std::list
. This allows traversal of the list in reverse order, starting from the last element and moving toward the first element. If the list is empty, the returned reverse iterator is equal to rend()
.
Syntax of std::list::rbegin
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;
Parameters
The std::list::rbegin
function does not take any parameters.
Return Value
Returns a reverse iterator (or a constant reverse iterator for const
lists) pointing to the last element of the list. If the list is empty, the returned reverse iterator is equal to rend()
.
Exceptions
The std::list::rbegin
function does not throw exceptions as it is marked noexcept
. However, dereferencing the reverse iterator returned by rbegin()
when the list is empty results in undefined behavior. It is recommended to check if the list is empty before accessing elements.
Examples for std::list::rbegin
Example 1: Traversing a List in Reverse Using std::list::rbegin
This example demonstrates iterating through the elements of a std::list
in reverse order using rbegin()
and rend()
:
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {10, 20, 30, 40, 50};
std::cout << "List elements in reverse: ";
for (auto it = myList.rbegin(); it != myList.rend(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- Define a list: A
std::list
namedmyList
is initialized with elements{10, 20, 30, 40, 50}
. - Use reverse iterators: The
rbegin()
function provides a reverse iterator pointing to the last element, andrend()
provides a reverse iterator one before the first element. - Iterate through the list: The
for
loop iterates fromrbegin()
torend()
, accessing and printing each element using the dereference operator (*it
).
Output:
List elements in reverse: 50 40 30 20 10
Example 2: Modifying Elements Using std::list::rbegin
This example demonstrates how to modify elements of a std::list
in reverse order using rbegin()
:
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {1, 2, 3, 4, 5};
auto it = myList.rbegin(); // Get a reverse iterator to the last element
*it = 10; // Modify the last element
std::cout << "Modified list: ";
for (const auto& elem : myList) {
std::cout << elem << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
- Define a list: A
std::list
namedmyList
is initialized with elements{1, 2, 3, 4, 5}
. - Get a reverse iterator: The
rbegin()
function provides a reverse iterator pointing to the last element. - Modify the last element: The value of the last element is updated to
10
using the reverse iterator. - Print the modified list: The updated list is printed using a range-based for loop.
Output:
Modified list: 1 2 3 4 10