std::string rend() method
- od C++20
- od C++11
- do C++11
// Non-const version
constexpr iterator rend() noexcept;
// Const version
constexpr const_iterator rend() const noexcept;
constexpr const_iterator crend() const noexcept;
// Non-const version
iterator rend() noexcept;
// Const version
const_iterator rend() const noexcept;
const_iterator crend() const noexcept;
// Non-const version
iterator rend();
// Const version
const_iterator rend() const;
It corresponds to the last element of the non-reversed string.
Returns a reverse iterator
to the last element of the reversed string. It corresponds to the element preceding the first element of the non-reversed string.Attempting to dereference a past-the-end iterator is undefined behaviour
.This method doesn't actually reverse the string, it just returns an iterator that points to the element before the first 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 rbegin()
.
Parameters
(none)
Return value
Reverse iterator to the first element.
Complexity
Constant - O(1)..
Difference between rend and crend
For a const container c
, rend and crend are the same - c.rend() == c.crend()
For non-const container of type c
they return different iterators:
- Non const container
- Const container
- rend
- crend
#include <string>
int main()
{
std::string str = "Hello";
auto it = str.rend(); // Type: std::string::reverse_iterator
*std::prev(it) = 'J'; // ✔ Ok
}
#include <string>
int main()
{
std::string str = "Hello";
auto it = str.crend(); // Type: std::string::reverse_const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}
- rend
- crend
#include <string>
int main()
{
const std::string str = "Hello";
auto it = str.rend(); // Type: std::string::reverse_const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}
#include <string>
int main()
{
const std::string str = "Hello";
auto it = str.crend(); // Type: std::string::reverse_const_iterator
*std::prev(it) = 'J'; // ❌ Error!
}
Example
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
int main()
{
std::string s("A man, a plan, a canal: Panama");
{
std::string c;
std::copy(s.rbegin(), s.rend(), std::back_inserter(c));
std::cout << c <<'\n'; // "amanaP :lanac a ,nalp a ,nam A"
}
{
std::string c;
std::copy(s.crbegin(), s.crend(), std::back_inserter(c));
std::cout << c <<'\n'; // "amanaP :lanac a ,nalp a ,nam A"
}
}
amanaP :lanac a ,nalp a ,nam A
amanaP :lanac a ,nalp a ,nam A
Hover to see the original license.