X Tutup
The Wayback Machine - https://web.archive.org/web/20240808230405/https://en.cppreference.com/w/cpp/utility/optional/begin
Namespaces
Variants
Views
Actions

std::optional<T>::begin

From cppreference.com
< cpp‎ | utility‎ | optional
 
 
Utilities library
Language support
Type support (basic types, RTTI)
Library feature-test macros (C++20)
Dynamic memory management
Program utilities
Coroutine support (C++20)
Variadic functions
Debugging support
(C++26)
Three-way comparison
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
General utilities
Date and time
Function objects
Formatting library (C++20)
(C++11)
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)   
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
Elementary string conversions
(C++17)
(C++17)

 
 
constexpr iterator begin() noexcept;
(since C++26)
constexpr const_iterator begin() const noexcept;
(since C++26)

If *this contains a value, returns an iterator to the contained value. Otherwise, a past-the-end iterator value.

range-begin-end.svg

Contents

[edit] Parameters

(none)

[edit] Return value

Iterator to the contained value if has_value() is true. Otherwise, a past-the-end iterator.

[edit] Complexity

Constant.

[edit] Notes

Feature-test macro Value Std Feature
__cpp_lib_optional_range_support 202406L (C++26) Range support for std::optional

[edit] Example

#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());
 
    // ranged-for loop support
    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);
}

Output:

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

[edit] See also

(C++26)
returns an iterator to the end
(public member function) [edit]
X Tutup