最終更新日時(UTC):
が更新

履歴 編集

function
<optional>

std::optional::begin(C++26)

constexpr iterator begin() noexcept; // (1)
constexpr const_iterator begin() const noexcept; // (2)

概要

optionalをrangeとした時の先頭要素を指すイテレータを取得する。

効果

has_value() == trueなら、保持している有効値を指すイテレータを返す。またこの時、distance(begin(), end()) == 1 となる。

has_value() != trueなら、末尾要素の次を指すイテレータを返す。この時、begin() == end() である。

#include <iostream>
#include <optional>

int main()
{
  std::optional<int> p1 = 1;
  for (auto i = p1.begin(); i != p1.end(); ++i) {
    std::cout << *i; // 1度通る
  }

  std::optional<int> p2 = std::null_opt;
  for (auto i = p2.begin(); i != p2.end(); ++i) {
    std::cout << *i; // 1度も通らない
  }
}

出力

1

バージョン

言語

  • C++26

処理系

参照