std::string rbegin() method
- since C++20
- since C++11
- until C++11
// Non-const version
constexpr iterator end() noexcept;
// Const version
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;
// Non-const version
iterator end() noexcept;
// Const version
const_iterator end() const noexcept;
const_iterator cend() const noexcept;
// Non-const version
iterator end();
// Const version
const_iterator end() const;
Returns a reverse iterator
to the first element of the reversed string.It corresponds to the last element of the non-reversed string.
This method doesn't actually reverse the string, it returns an iterator that points to the last element of the string,
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
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 <string>
int main()
{
std::string str = "Hello";
auto it = str.rbegin(); // Type: std::string::reverse_iterator
*it = 'J'; // ✔ Ok
}
#include <string>
int main()
{
std::string str = "Hello";
auto it = str.crbegin(); // Type: std::string::reverse_const_iterator
*it = 'J'; // ❌ Error!
}
- rbegin
- crbegin
#include <string>
int main()
{
const std::string str = "Hello";
auto it = str.rbegin(); // Type: std::string::reverse_const_iterator
*it = 'J'; // ❌ Error!
}
#include <string>
int main()
{
const std::string str = "Hello";
auto it = str.crbegin(); // Type: std::string::reverse_const_iterator
*it = 'J'; // ❌ Error!
}
Example
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
int main()
{
std::string s("Exemplar!");
*s.rbegin() = 'y';
std::cout << s << '\n'; // "Exemplary"
std::string c;
std::copy(s.crbegin(), s.crend(), std::back_inserter(c));
std::cout << c << '\n'; // "yralpmexE"
}
Exemplary
yralpmexE
Hover to see the original license.