std::vector rend() 方法
- 自 C++20 起
- 自 C++11 起
- 直到 C++11
// prism-push-types:iterator,const_iterator
// Non-const version
constexpr iterator rend() noexcept;
// Const version
constexpr const_iterator rend() const noexcept;
constexpr const_iterator crend() const noexcept;
// prism-push-types:iterator,const_iterator
// Non-const version
iterator rend() noexcept;
// Const version
const_iterator rend() const noexcept;
const_iterator crend() const noexcept;
// prism-push-types:iterator,const_iterator
// Non-const version
iterator rend();
// Const version
const_iterator rend() const;
返回一个反向迭代器
指向反向容器的最后一个元素。它对应于非反向容器的第一个元素**之前**的元素。
它实际上返回一个指向原始容器末尾之后的迭代器。
未定义行为
尝试解引用“past-the-end”迭代器是未定义行为
.注意
此方法实际上不会反转向量,它只是返回一个指向数组第一个元素之前的元素的迭代器,并且其+
、-
、--
、++
运算符的实现略有不同。
例如,it++
会递减内部指针,而it--
会递增内部指针(以便以相反的顺序遍历容器实际工作)。
如果容器为空,则返回的迭代器将等于rbegin()
。
参数
(无)
返回值
指向第一个元素的反向迭代器。
复杂度
常数 - O(1)。
rend 和 crend 的区别
对于常量容器c
,rend 和 crend 是相同的 - c.rend() == c.crend()
对于非常量类型c
的容器,它们返回不同的迭代器
- 非常量容器
- 常量容器
- rend
- crend
#include <vector>
int main()
{
std::vector<int> arr = {1, 2, 3, 4, 5};
auto it = arr.rend(); // Type: std::vector<int>::reverse_iterator
*std::prev(it) = 5; // ✔ Ok
}
#include <vector>
int main()
{
std::vector<int> arr = {1, 2, 3, 4, 5};
auto it = arr.crend(); // Type: std::vector<int>::reverse_const_iterator
*std::prev(it) = 5; // ❌ Error!
}
- rend
- crend
#include <vector>
int main()
{
const std::vector<int> arr = {1, 2, 3, 4, 5};
auto it = arr.rend(); // Type: std::vector<int>::reverse_const_iterator
*std::prev(it) = 5; // ❌ Error!
}
#include <vector>
int main()
{
const std::vector<int> arr = {1, 2, 3, 4, 5};
auto it = arr.crend(); // Type: std::vector<int>::reverse_const_iterator
*std::prev(it) = 5; // ❌ Error!
}
示例
Main.cpp
#include <algorithm>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
int main()
{
std::vector<int> nums {1, 2, 4, 8, 16};
std::vector<std::string> fruits {"orange", "apple", "raspberry"};
std::vector<char> empty;
// Print vector.
std::for_each(nums.rbegin(), nums.rend(), [](const int n) { std::cout << n << ' '; });
std::cout << '\n';
// Sums all integers in the vector nums (if any), printing only the result.
std::cout << "Sum of nums: "
<< std::accumulate(nums.rbegin(), nums.rend(), 0) << '\n';
// Prints the first fruit in the vector fruits, checking if there is any.
if (!fruits.empty())
std::cout << "First fruit: " << *fruits.rbegin() << '\n';
if (empty.rbegin() == empty.rend())
std::cout << "vector 'empty' is indeed empty.\n";
}
输出
16 8 4 2 1
Sum of nums: 31
First fruit: raspberry
vector 'empty' is indeed empty.