跳到主要内容

std::string_view rbegin() 方法

// 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::stringstd::vector)不同,rbegincrbegin 都返回相同的迭代器。

#include <string_view>

int main()
{
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
本文源自此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。

std::string_view rbegin() 方法

// 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::stringstd::vector)不同,rbegincrbegin 都返回相同的迭代器。

#include <string_view>

int main()
{
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
本文源自此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。点击“编辑此页面”查看本文档的所有更改。
悬停查看原始许可证。