# std::optional<T>::begin

> C++ Atlas: `cppatlas.com/w/cpp/utility/optional/begin` | Source: https://en.cppreference.com/w/cpp/utility/optional/begin | Domain: Utility | Standards: C++26

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

## Official Specification Summary (cppreference)

```cpp
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.

### Parameters

(none)

### Return value

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

### Complexity

Constant.

### Notes

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

### Example

```cpp
#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:

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

### See also

- [`end`](https://en.cppreference.com/w/cpp/utility/optional/end) (C++26): returns an iterator to the end (public member function)

---
Attribution: content from https://en.cppreference.com/w/cpp/utility/optional/begin (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.