Namespaces
Variants

std::list<T,Allocator>:: rend, std::list<T,Allocator>:: crend

From zh.cppreference.net

reverse_iterator rend ( ) ;
(1) (自 C++11 起为 noexcept)
(自 C++26 起为 constexpr)
const_reverse_iterator rend ( ) const ;
(2) (自 C++11 起为 noexcept)
(自 C++26 起为 constexpr)
const_reverse_iterator crend ( ) const noexcept ;
(3) (自 C++11 起)
(自 C++26 起为 constexpr)

返回一个反向迭代器,指向反转后 * this 的最后一个元素之后的位置。它对应于非反转 * this 的第一个元素之前的位置。

此返回的迭代器仅作为哨兵使用。不保证其具有 可解引用性 。

range-rbegin-rend.svg

目录

返回值

指向最后一个元素之后元素的反向迭代器。

复杂度

常量。

注释

libc++ 向后移植 crend() 至 C++98 模式。

示例

#include <algorithm>
#include <cassert>
#include <iostream>
#include <numeric>
#include <string>
#include <list>

int main()
{
    std::list<int> nums{1, 2, 4, 8, 16};
    std::list<std::string> fruits{"orange", "apple", "raspberry"};
    std::list<char> empty;

    // Print list nums.
    std::for_each(nums.crbegin(), nums.crend(),
                  [](const int n) { std::cout << n << ' '; });
    std::cout << '\n';

    // Sum all integers in the list nums, printing only the result.
    std::cout << "Sum of nums: "
              << std::accumulate(nums.crbegin(), nums.crend(), 0) << '\n';

    // Print the last fruit in the list fruits, checking if there is any.
    if (!fruits.empty())
        std::cout << "Last fruit: " << *fruits.crbegin() << '\n';

    if (empty.crbegin() == empty.crend())
        std::cout << "list ‘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
list ‘empty’ is indeed empty.

另请参阅

返回指向起始的反向迭代器
(公开成员函数)
(C++14)
返回容器或数组的逆向末端迭代器
(函数模板)