Namespaces
Variants

std::optional<T>:: begin

From cppreference.net
Utilities library
constexpr iterator begin ( ) noexcept ;
(C++26以降)
constexpr const_iterator begin ( ) const noexcept ;
(C++26以降)

* this が値を含む場合、含まれる値へのイテレータを返します。それ以外の場合、終端イテレータ値を返します。

range-begin-end.svg

目次

戻り値

has_value ( ) true の場合、格納されている値へのイテレータ。それ以外の場合、末尾後イテレータ。

計算量

定数。

注記

機能テスト マクロ 標準 機能
__cpp_lib_optional_range_support 202406L (C++26) std::optional の レンジサポート

#include <optional>
#include <print>
#include <vector>
int main()
{
    constexpr std::optional<int> none{std::nullopt};
    constexpr std::optional<int> some{42};
    static_assert(none.begin() == none.end());
    static_assert(some.begin() != some.end());
    // 範囲ベースforループのサポート
    for (int i : none)
        std::println("'none' has a value of {}", i);
    for (int i : some)
        std::println("'some' has a value of {}", i);
    std::optional<std::vector<int>> many({0, 1, 2});
    for (const auto& v : many)
        std::println("'many' has a value of {}", v);
}

出力:

'some' has a value of 42
'many' has a value of [0, 1, 2]

関連項目

(C++26)
終端を指すイテレータを返す
(公開メンバ関数)