std::string rbegin() 方法
- 自 C++20 起
- 自 C++11 起
- 直到 C++11
// Non-const version
constexpr iterator end() noexcept;
// Const version
constexpr const_iterator end() const noexcept;
constexpr const_iterator cend() const noexcept;
// Non-const version
iterator end() noexcept;
// Const version
const_iterator end() const noexcept;
const_iterator cend() const noexcept;
// Non-const version
iterator end();
// Const version
const_iterator end() const;
返回一个反向迭代器
指向反转字符串的第一个元素。它对应于非反转字符串的最后一个元素。
注意
此方法实际上并未反转字符串,它返回一个指向字符串最后一个元素的迭代器,并且其 +
、-
、--
、++
运算符的实现略有改变。
例如,it++
会递减内部指针,而it--
会递增内部指针(以便以相反的顺序遍历容器实际工作)。
如果容器为空,则返回的迭代器将等于 rend()
。
参数
(无)
返回值
指向第一个元素的反向迭代器。
复杂度
常数 - O(1)。
rbegin 和 crbegin 之间的区别
对于 const 容器 c
,rbegin 和 crbegin 相同 - c.rbegin() == c.crbegin()
对于非常量类型c
的容器,它们返回不同的迭代器
- 非常量容器
- 常量容器
- rbegin
- crbegin
#include <string>
int main()
{
std::string str = "Hello";
auto it = str.rbegin(); // Type: std::string::reverse_iterator
*it = 'J'; // ✔ Ok
}
#include <string>
int main()
{
std::string str = "Hello";
auto it = str.crbegin(); // Type: std::string::reverse_const_iterator
*it = 'J'; // ❌ Error!
}
- rbegin
- crbegin
#include <string>
int main()
{
const std::string str = "Hello";
auto it = str.rbegin(); // Type: std::string::reverse_const_iterator
*it = 'J'; // ❌ Error!
}
#include <string>
int main()
{
const std::string str = "Hello";
auto it = str.crbegin(); // Type: std::string::reverse_const_iterator
*it = 'J'; // ❌ Error!
}
示例
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