std::rend, std::crend_C++中文网

C++ 参考手册

位置:首页 > C++ 参考手册 >迭代器库 > std::rend, std::crend

返回值向给定容器 c 或数组 array 逆向结尾的迭代器。

1) 返回指向容器 c 逆向结尾的可能有 const 限定的迭代器。
2) 返回指向数组 array 逆向结尾的 std::reverse_iterator<T*> 。
3) 返回指向容器 c 逆向结尾的 const 限定的迭代器。

range-rbegin-rend.svg

参数

c - 拥有 rend 方法的容器
array - 任意类型的数组

返回值

指向 c 或 array 逆向结尾的迭代器

注意

除了包含于 <iterator> ,若包含下列任一头文件,则保证 std::rend 与 std::crend 可用: <array> 、 <deque> 、 <forward_list> 、 <list> 、 <map> 、 <regex> 、 <set> 、 <span> (C++20 起) 、 <string> 、 <string_view> (C++17 起) 、 <unordered_map> 、 <unordered_set> 及 <vector> 。

重载

可以为未暴露适合的 rend() 成员函数的类提供 rend 的自定义重载,使之亦能迭代。标准库已经提供了下列重载:

特化 std::rend
(函数)

示例

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
 
int main()
{
    int a[] = {4, 6, -3, 9, 10};
    std::cout << "Array backwards: ";
    std::copy(std::rbegin(a), std::rend(a), std::ostream_iterator<int>(std::cout, " "));
 
    std::cout << "\nVector backwards: ";
    std::vector<int> v = {4, 6, -3, 9, 10};
    std::copy(std::rbegin(v), std::rend(v), std::ostream_iterator<int>(std::cout, " "));
}

输出:

Array backwards: 10 9 -3 6 4 
Vector backwards: 10 9 -3 6 4

参阅