std::vector<T,Allocator>::rbegin, std::vector<T,Allocator>::crbegin
来自 zh.cppreference.net
reverse_iterator rbegin();
|
(1) | (自 C++11 起 noexcept) (自 C++20 起 constexpr) |
const_reverse_iterator rbegin() const;
|
(2) | (自 C++11 起 noexcept) (自 C++20 起 constexpr) |
const_reverse_iterator crbegin() const noexcept;
|
(3) | (自 C++11 起) (自 C++20 起 constexpr) |
返回指向反向容器的第一个元素的逆向迭代器vector。它对应于非反向容器的最后一个元素vector。如果该vector为空,则返回的迭代器等于rend()。
返回值
指向第一个元素的反向迭代器。
复杂度
常量。
注释
返回的反向迭代器的 底层迭代器 是 end 迭代器 。因此当 end 迭代器失效时,返回的迭代器也会同时失效。
libc++ 向后移植
crbegin()
至 C++98 模式。
示例
运行此代码
#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;
// Print vector nums.
std::for_each(nums.crbegin(), nums.crend(),
[](const int n) { std::cout << n << ' '; });
std::cout << '\n';
// Sum all integers in the vector nums, printing only the result.
std::cout << "Sum of nums: "
<< std::accumulate(nums.crbegin(), nums.crend(), 0) << '\n';
// Print the last fruit in the vector fruits, checking if there is any.
if (!fruits.empty())
std::cout << "Last fruit: " << *fruits.crbegin() << '\n';
if (empty.crbegin() == empty.crend())
std::cout << "vector ‘empty’ is indeed empty.\n";
// Modify the last element in nums.
*nums.rbegin() = 32;
assert(*nums.crbegin() == 32);
}
输出:
16 8 4 2 1
Sum of nums: 31
Last fruit: raspberry
vector ‘empty’ is indeed empty.
参见
|
(C++11)
|
返回指向末尾的反向迭代器
(公开成员函数) |
|
(C++14)
|
返回指向容器或数组起始位置的反向迭代器
(函数模板) |