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

履歴 編集

function
<span>

std::span::begin(C++20)

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

friend constexpr iterator begin(span s) noexcept; // (2)

概要

先頭要素を指すイテレータを取得する。

  • (1) : メンバ関数として、先頭要素を指すイテレータを取得する
  • (2) : ADLで探索される関数として、先頭要素を指すイテレータを取得する

戻り値

  • (1) : spanオブジェクトが参照している範囲の、最初の要素を参照するイテレータを返す。empty()trueである場合、end()と同じ値が返る
  • (2) : return s.begin();

例外

投げない

計算量

定数時間

#include <iostream>
#include <span>
#include <vector>
#include <algorithm>

int main()
{
  std::vector<int> v = {1, 2, 3, 4, 5};

  // vの先頭3要素を部分シーケンスとして参照する
  std::span<int> s = std::span(v).first(3);

  // (1)
  std::for_each(s.begin(), s.end(), [](int x) {
    std::cout << x << ',';
  });
  std::cout << std::endl;

  // (2) 名前空間修飾なしで、ADLで呼び出す
  std::for_each(begin(s), end(s), [](int x) {
    std::cout << x << ',';
  });
  std::cout << std::endl;

  // (1)に対する、<iterator>で定義される汎用的なstd::begin()/std::end()の呼び出し
  std::for_each(std::begin(s), std::end(s), [](int x) {
    std::cout << x << ',';
  });
  std::cout << std::endl;

  // (2) 範囲for文は、ADLでbegin()/end()を探索する
  for (int x : s) {
    std::cout << x << ',';
  }
  std::cout << std::endl;
}

出力

1,2,3,
1,2,3,
1,2,3,
1,2,3,

バージョン

言語

  • C++20

処理系

参照