Namespaces
Variants

std::optional<T>:: begin

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

Wenn * this einen Wert enthält, gibt es einen Iterator zum enthaltenen Wert zurück. Andernfalls einen Iteratorwert, der über das Ende hinausweist.

range-begin-end.svg

Inhaltsverzeichnis

Rückgabewert

Iterator zum enthaltenen Wert, falls has_value ( ) gleich true ist. Andernfalls ein Past-the-End-Iterator.

Komplexität

Konstante.

Hinweise

Feature-Test Makro Wert Std Funktion
__cpp_lib_optional_range_support 202406L (C++26) Bereichsunterstützung für std::optional

Beispiel

#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());
    // Unterstützung für Range-basierte for-Schleifen
    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);
}

Ausgabe:

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

Siehe auch

(C++26)
gibt einen Iterator zum Ende zurück
(öffentliche Elementfunktion)