std::string_view rbegin() method
- since C++17
// Const version only
constexpr const iterator rbegin() const noexcept;
// Const version only
constexpr const_iterator crbegin() const noexcept;
Returns a reverse iterator
to the first element of the reversed view.It corresponds to the last element of the original view.
This method doesn't actually reverse the view, it returns an iterator that points to the last element of the view,
and which +
, -
, --
, ++
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 - O(1).
Difference between rbegin and crbegin
Unlike for other containers, like std::string
or std::vector
, rbegin
and crbegin
both return the same iterator.
- Non const container
- Const container
- rbegin
- crbegin
#include <string_view>
int main()
{
std::string_view str = "Hello";
auto it = str.crbegin(); // Type: std::string_view::reverse_const_iterator
*it = 'J'; // ❌ Error!
}
#include <string_view>
int main()
{
std::string_view str = "Hello";
auto it = str.crbegin(); // Type: std::string_view::reverse_const_iterator
*it = 'J'; // ❌ Error!
}
- rbegin
- crbegin
#include <string_view>
int main()
{
const std::string_view str = "Hello";
auto it = str.rbegin(); // Type: std::string_view::reverse_const_iterator
*it = 'J'; // ❌ Error!
}
#include <string_view>
int main()
{
const std::string_view str = "Hello";
auto it = str.crbegin(); // Type: std::string_view::reverse_const_iterator
*it = 'J'; // ❌ Error!
}
Example
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string_view>
int main()
{
std::ostream_iterator<char> out_it(std::cout);
std::string_view str_view("abcdef");
std::copy(str_view.rbegin(), std::next(str_view.rbegin(), 3), out_it);
*out_it = '\n';
std::copy(str_view.crbegin(), std::next(str_view.crbegin(), 3), out_it);
*out_i
}
fed
fed
Hover to see the original license.