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 인 경우 포함된 값에 대한 반복자. 그렇지 않으면 past-the-end 반복자.

복잡도

상수.

참고 사항

기능 테스트 매크로 표준 기능
__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)
끝을 가리키는 반복자를 반환합니다
(public member function)