跳到主要内容

std::string rbegin() 方法

// Non-const version
constexpr iterator end() noexcept;

// Const version
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;

返回一个反向迭代器

指向反转字符串的第一个元素。
它对应于非反转字符串的最后一个元素。

注意

此方法实际上并未反转字符串,它返回一个指向字符串最后一个元素的迭代器,并且其 +---++ 运算符的实现略有改变。

例如,it++会递减内部指针,而it--会递增内部指针(以便以相反的顺序遍历容器实际工作)。

如果容器为空,则返回的迭代器将等于 rend()

参数

(无)

返回值

指向第一个元素的反向迭代器。

复杂度

常数 - O(1)

rbegin 和 crbegin 之间的区别

对于 const 容器 c,rbegin 和 crbegin 相同 - c.rbegin() == c.crbegin()

对于非常量类型c的容器,它们返回不同的迭代器

#include <string>

int main()
{
std::string str = "Hello";
auto it = str.rbegin(); // Type: std::string::reverse_iterator
*it = 'J'; // ✔ Ok
}

示例

Main.cpp
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>

int main()
{
std::string s("Exemplar!");
*s.rbegin() = 'y';
std::cout << s << '\n'; // "Exemplary"

std::string c;
std::copy(s.crbegin(), s.crend(), std::back_inserter(c));
std::cout << c << '\n'; // "yralpmexE"
}
输出
Exemplary
yralpmexE
本文源自 此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。单击“编辑此页面”以查看此文档的所有更改。
悬停查看原始许可证。

std::string rbegin() 方法

// Non-const version
constexpr iterator end() noexcept;

// Const version
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;

返回一个反向迭代器

指向反转字符串的第一个元素。
它对应于非反转字符串的最后一个元素。

注意

此方法实际上并未反转字符串,它返回一个指向字符串最后一个元素的迭代器,并且其 +---++ 运算符的实现略有改变。

例如,it++会递减内部指针,而it--会递增内部指针(以便以相反的顺序遍历容器实际工作)。

如果容器为空,则返回的迭代器将等于 rend()

参数

(无)

返回值

指向第一个元素的反向迭代器。

复杂度

常数 - O(1)

rbegin 和 crbegin 之间的区别

对于 const 容器 c,rbegin 和 crbegin 相同 - c.rbegin() == c.crbegin()

对于非常量类型c的容器,它们返回不同的迭代器

#include <string>

int main()
{
std::string str = "Hello";
auto it = str.rbegin(); // Type: std::string::reverse_iterator
*it = 'J'; // ✔ Ok
}

示例

Main.cpp
#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>

int main()
{
std::string s("Exemplar!");
*s.rbegin() = 'y';
std::cout << s << '\n'; // "Exemplary"

std::string c;
std::copy(s.crbegin(), s.crend(), std::back_inserter(c));
std::cout << c << '\n'; // "yralpmexE"
}
输出
Exemplary
yralpmexE
本文源自 此 CppReference 页面。它可能为了改进或编辑者偏好而进行了修改。单击“编辑此页面”以查看此文档的所有更改。
悬停查看原始许可证。