Namespaces
Variants

std::list<T,Allocator>:: rbegin, std::list<T,Allocator>:: crbegin

From ja.cppreference.net

reverse_iterator rbegin ( ) ;
(1) (C++11以降 noexcept)
(C++26以降 constexpr)
const_reverse_iterator rbegin ( ) const ;
(2) (C++11以降 noexcept)
(C++26以降 constexpr)
const_reverse_iterator crbegin ( ) const noexcept ;
(3) (C++11以降)
(C++26以降 constexpr)

反転された * this の最初の要素を指す逆方向イテレータを返します。これは非反転 * this の最後の要素に対応します。

* this が空の場合、返されるイテレータは rend() と等しくなります。

range-rbegin-rend.svg

目次

戻り値

最初の要素への逆方向イテレータ。

計算量

定数。

注記

返される逆イテレータの 基盤となるイテレータ endイテレータ です。したがって、endイテレータが無効化された場合、返されるイテレータも無効化されます。

libc++は crbegin() を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++11)
末尾を指す逆イテレータを返す
(public member function)
コンテナまたは配列の先頭を指す逆イテレータを返す
(function template)