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