GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::size - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. iterator
  3. size

最終更新日時: 2026年09月11日 13時06分31秒 (JST)
Akira Takahashi が更新

履歴 編集

function template
<iterator>

std::size(C++17)

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

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

概要

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

戻り値

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

備考

  • 機能テストマクロは__cpp_lib_nonmember_container_accessで値は201411
  • <iterator>ヘッダを読み込む以外では、以下のヘッダが読み込まれている場合に、この関数を使用できる:
    • <array>
    • <deque>
    • <flat_map> (C++26)
    • <flat_set> (C++26)
    • <forward_list>
    • <hive> (C++26)
    • <inplace_vector> (C++26)
    • <list>
    • <map>
    • <regex>
    • <set>
    • <simd> (C++29)
    • <span> (C++20)
    • <string>
    • <string_view> (C++20)
    • <unordered_map>
    • <unordered_set>
    • <vector>

例

#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

詳細

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

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

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

バージョン

言語

  • C++17

処理系

  • Clang: 3.6 ✅
  • GCC: 6.1 ✅
  • Visual C++: 2015 ✅

関連項目

  • std::ranges::size

参照

  • boost::size() - Boost Range Library
  • N4280: Non-member size() and more (Revision 2)
  • LWG Issue 3009. Including <string_view> doesn't provide std::size/empty/data
  • P3016R6 Resolve inconsistencies in begin/end for valarray and braced-initializer-list
  • LWG Issue 4385. Including <simd> doesn't provide std::begin/end
    • この関数テンプレートが利用可能になるヘッダの一覧に<simd>が追加された。規格としてはC++29のワーキングドラフトへ適用されたが、<simd>が追加されたC++26で記載が漏れていたものであるため、C++26へ遡及して適用される
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.