std::string_view rend() method
- od C++17
// Const version onlyconstexpr const iterator rend() const noexcept;// Const version onlyconstexpr const_iterator crend() const noexcept;Returns a reverse iterator
to the last element of the reversed view.It corresponds to the element preceding the first element of the original view.
Attempting to dereference a past the end iterator is undefined behaviour
.This method doesn't actually reverse the view, it just returns an iterator that points to the element before the first 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 rbegin().
Parameters
(none)
Return value
Reverse iterator to the first element.
Complexity
Constant - O(1)..
Difference between rend and crend
Unlike for other containers, like std::string or std::vector, rend and crend both return the same iterator.
- Non const container
- Const container
- rend
- crend
#include <string_view> int main(){ std::string_view str = "Hello"; auto it = str.crend(); // Type: std::string_view::reverse_const_iterator *std::prev(it) = 'J'; // ❌ Error! }#include <string_view>int main(){ std::string_view str = "Hello"; auto it = str.crend(); // Type: std::string_view::reverse_const_iterator *std::prev(it) = 'J'; // ❌ Error! }- rend
- crend
#include <string_view>int main(){ const std::string_view str = "Hello"; auto it = str.rend(); // Type: std::string_view::reverse_const_iterator *std::prev(it) = 'J'; // ❌ Error! }#include <string_view>int main(){ const std::string_view str = "Hello"; auto it = str.crend(); // Type: std::string_view::reverse_const_iterator *std::prev(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(), str_view.rend(), out_it); *out_it = '\n'; std::copy(str_view.crbegin(), str_view.crend(), out_it); *out_it = '\n';}fedcbafedcbaHover to see the original license.