Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::optional<T>::begin

      From cppreference.com
      <cpp‎ |utility‎ |optional
       
       
      Utilities library
       
       
      constexpr iterator begin()noexcept;
      (since C++26)
      constexpr const_iterator begin()constnoexcept;
      (since C++26)

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

      range-begin-end.svg

      Contents

      [edit]Return value

      Iterator to the contained value ifhas_value() istrue. Otherwise, a past-the-end iterator.

      [edit]Complexity

      Constant.

      [edit]Notes

      Feature-test macroValueStdFeature
      __cpp_lib_optional_range_support202406L(C++26)Range support forstd::optional

      [edit]Example

      Run this code
      #include <optional>#include <print>#include <vector> int main(){constexprstd::optional<int> none{std::nullopt};constexprstd::optional<int> some{42};     static_assert(none.begin()== none.end());    static_assert(some.begin()!= some.end()); // ranged-for loop supportfor(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(constauto& v: many)std::println("'many' has a value of {}", v);}

      Output:

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

      [edit]See also

      (C++26)
      returns an iterator to the end
      (public member function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/optional/begin&oldid=182155"

      [8]ページ先頭

      ©2009-2025 Movatter.jp