命名空间
变体
操作

std::optional<T>::begin

来自 cppreference.cn
< cpp‎ | utility‎ | optional
 
 
 
 
constexpr iterator begin() noexcept;
(自 C++26 起)
constexpr const_iterator begin() const noexcept;
(自 C++26 起)

如果 *this 包含值,则返回指向所含值的迭代器。否则,返回一个过尾迭代器值。

range-begin-end.svg

内容

[编辑] 参数

(无)

[编辑] 返回值

如果 has_value()true,则为指向所含值的迭代器。否则,为过尾迭代器。

[编辑] 复杂度

常数。

[编辑] 注解

特性测试 Std 特性
__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());
 
    // 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);
}

输出

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

[编辑] 参见

(C++26)
返回指向末尾的迭代器
(公开成员函数) [编辑]