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

履歴 編集

function template
<iterator>

std::size(C++17)

namespace std {
  template <class C>
  constexpr auto size(const C& c) -> decltype(c.size());    // (1)

  template <class T, std::size_t N>
  constexpr std::size_t size(const T (&array)[N]) noexcept; // (2)
}

概要

コンテナの要素数を取得する。

戻り値

  • (1) : return c.size();
  • (2) : return N;

備考

#include <vector>
#include <iostream>

int main()
{
  int arr[4] = {};
  std::cout << std::size(arr) << std::endl;

  std::cout << std::size(u8"arikitari") << std::endl;

  std::vector<int> v = { 1,1,2,3,5,8 };
  int hoge = 13;
  v.push_back(hoge);
  std::cout << std::size(v) << std::endl;

  //変数vの型はstd名前空間にあるクラス型なので
  //ADLによって `std::`がなくとも発見できる
  std::cout << size(v) << std::endl;
}

出力

4
10
7
7

詳細

これまで_countofnumof, arraySizeOf, ARRAY_SIZE, ARRAY_LENGTH等の名前で配列の要素数を求めるために、概ね次のようなマクロが利用されてきた。

#define COUNTOF(array) (sizeof(array) / sizeof(array[0]))

std::size()はこれを置き換えるものである。

バージョン

言語

  • C++17

処理系

関連項目

参照