std::vector<T,Allocator>::rbegin, std::vector<T,Allocator>::crbegin
来自cppreference.com
| (1) | (C++11 起为 noexcept) (C++20 起为 constexpr) |
|
| (2) | (C++11 起为 noexcept) (C++20 起为 constexpr) |
|
| (3) | (C++11 起) (C++20 起为 constexpr) |
|
返回指向逆向的 vector 的首元素的逆向迭代器。它对应非逆向 vector 的末元素。如果 vector 为空,那么返回的迭代器等于 rend()。
返回值
指向首元素的逆向迭代器。
复杂度
常数。
注解
返回的逆向迭代器的底层迭代器是尾迭代器。因此在尾迭代器失效时,返回的迭代器也会失效。
libc++ 将 crbegin() 向后移植到 C++98 模式。
示例
Run this code
#include <algorithm>
#include <cassert>
#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;
// 打印 vector nums。
std::for_each(nums.crbegin(), nums.crend(),
[](const int n) { std::cout << n << ' '; });
std::cout << '\n';
// 求和 vector nums 中的所有整数,仅打印结果。
std::cout << "求和 nums: "
<< std::accumulate(nums.crbegin(), nums.crend(), 0) << '\n';
// 打印 vector fruits 中的最后一个水果,不检查是否有一个。
if (!fruits.empty())
std::cout << "最后一个水果: " << *fruits.crbegin() << '\n';
if (empty.crbegin() == empty.crend())
std::cout << "vector ‘empty’ 确实是空的。\n";
// 修改 nums 中的最后一个元素。
*nums.rbegin() = 32;
assert(*nums.crbegin() == 32);
}
输出:
16 8 4 2 1
求和 nums: 31
最后一个水果: raspberry
vector 'empty' 确实是空的。
参阅
(C++11) |
返回指向末尾的逆向迭代器 (公开成员函数) |
(C++14) |
返回指向一个容器或数组的逆向迭代器 (函数模板) |