std::optional<T>:: begin
From cppreference.net
C++
Utilities library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::optional
| Member functions | ||||
| Observers | ||||
| Iterators | ||||
|
optional::begin
(C++26)
|
||||
|
(C++26)
|
||||
| Monadic operations | ||||
|
(C++23)
|
||||
|
(C++23)
|
||||
|
(C++23)
|
||||
| Modifiers | ||||
| Non-member functions | ||||
| Deduction guides | ||||
| Helper classes | ||||
| Helper objects | ||||
|
constexpr
iterator begin
(
)
noexcept
;
|
(自 C++26 起) | |
|
constexpr
const_iterator begin
(
)
const
noexcept
;
|
(自 C++26 起) | |
如果 * this 包含值,则返回指向所含值的迭代器。否则,返回尾后迭代器值。
目录 |
返回值
若 has_value ( ) 为 true ,则返回指向所含值的迭代器。否则返回逾尾迭代器。
复杂度
常量。
注释
| 功能测试 宏 | 值 | 标准 | 功能 |
|---|---|---|---|
__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)
|
返回指向末尾的迭代器
(公开成员函数) |