std::array rbegin()/crbegin() method
- since C++17
- until C++17
// Non-const version
constexpr iterator rbegin() noexcept;
// Const version
constexpr const_iterator rbegin() const noexcept;
constexpr const_iterator crbegin() const noexcept;
// Non-const version
iterator rbegin() noexcept;
// Const version
const_iterator rbegin() const noexcept;
const_iterator crbegin() const noexcept;
Returns a reverse iterator
to the first element of the reversed array. It corresponds to the last element of the non-reversed array.This method doesn't actually reverse the array, it just returns an iterator that points to the last element of the array,
and whose +
, -
, --
, ++
operators have slightly changed implementations.
For example it++
decrements the internal pointer and it--
increments it (so that traversing the container in a reverse order actually works).
If the container is empty, the returned iterator will be equal to rend()
.
Parameters
(none)
Return value
Reverse iterator to the first element.
Complexity
Constant.
Difference between rbegin and crbegin
For a const container c
, rbegin and crbegin are the same - c.rbegin() == c.crbegin()
For non-const container of type c
they return different iterators:
- Non const container
- Const container
- rbegin
- crbegin
#include <array>
int main()
{
std::array<int, 5> arr = {1, 2, 3, 4, 5};
auto it = arr.rbegin(); // Type: std::array<int, 5>::reverse_iterator
*it = 5; // ✔ Ok
}
#include <array>
int main()
{
std::array<int, 5> arr = {1, 2, 3, 4, 5};
auto it = arr.crbegin(); // Type: std::array<int, 5>::reverse_const_iterator
// ❌ Error!
*it = 5;
}
- rbegin
- crbegin
#include <array>
int main()
{
const std::array<int, 5> arr = {1, 2, 3, 4, 5};
auto it = arr.rbegin(); // Type: std::array<int, 5>::reverse_const_iterator
// ❌ Error!
*it = 5;
}
#include <array>
int main()
{
const std::array<int, 5> arr = {1, 2, 3, 4, 5};
auto it = arr.crbegin(); // Type: std::array<int, 5>::reverse_const_iterator
// ❌ Error!
*it = 5;
}
Example
#include <algorithm>
#include <iostream>
#include <string>
#include <string_view>
#include <array>
int main()
{
constexpr std::array<std::string_view, 8> data = {"▁","▂","▃","▄","▅","▆","▇","█"};
std::array<std::string, std::size(data)> arr;
std::copy(data.cbegin(), data.cend(), arr.begin());
// ^ ^ ^
auto print = [](const std::string_view s) { std::cout << s << ' '; };
print("Print 'arr' in direct order using [cbegin, cend):\t");
std::for_each(arr.cbegin(), arr.cend(), print);
// ^ ^
print("\n\nPrint 'arr' in reverse order using [crbegin, crend):\t");
std::for_each(arr.crbegin(), arr.crend(), print);
// ^^ ^^
print("\n");
}
Print 'arr' in direct order using [cbegin, cend): ▁ ▂ ▃ ▄ ▅ ▆ ▇ █
Print 'arr' in reverse order using [crbegin, crend): █ ▇ ▆ ▅ ▄ ▃ ▂ ▁
Hover to see the original license.