Namespaces
Variants

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

ja.cppreference.net より

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

逆順にした vector の最初の要素を指す逆イテレータを返します。非逆順の vector の最後の要素に対応します。vector が空の場合、返されるイテレータは rend() と等しくなります。

戻り値

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

計算量

定数。

注記

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

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