std::optional<T>::begin
來自 cppreference.com
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()); // 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) |
返回指向末尾的迭代器 (public member function) |