std::string_view rend() 方法
- 自 C++17 起
// Const version only
constexpr const iterator rend() const noexcept;
// Const version only
constexpr const_iterator crend() const noexcept;
返回一个反向迭代器
指向反向视图的最后一个元素。它对应于原始视图的第一个元素**之前**的元素。
未定义行为
尝试解引用越界迭代器是未定义行为
.注意
此方法实际上并未反转视图,它只是返回一个指向视图第一个元素之前元素的迭代器,并且其+
、-
、--
、++
运算符的实现略有改变。
例如,it++
会递减内部指针,而it--
会递增内部指针(以便以相反的顺序遍历容器实际工作)。
如果容器为空,则返回的迭代器将等于rbegin()
。
参数
(无)
返回值
指向第一个元素的反向迭代器。
复杂度
常数 - O(1)。
rend 和 crend 的区别
与std::string
或std::vector
等其他容器不同,rend
和crend
都返回相同的迭代器。
- 非常量容器
- 常量容器
- 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!
}
示例
Main.cpp
#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';
}
输出
fedcba
fedcba