• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

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

    履歴 編集

    function
    <vector>

    std::vector::capacity

    size_type capacity() const;                    // (1) C++03
    size_type capacity() const noexcept;           // (1) C++11
    constexpr size_type capacity() const noexcept; // (1) C++20
    

    概要

    メモリを再確保せずに格納できる最大の要素数を取得する

    戻り値

    メモリの再確保をすることなく保持することができる最大の要素数

    計算量

    定数時間

    #include <iostream>
    #include <vector>
    
    int main()
    {
      // 確保した領域を確認
      {
        std::vector<int> v;
        v.reserve(3);
    
        std::size_t cap = v.capacity();
        std::cout << cap << std::endl;
      }
    
      // 要素を削除しただけでは領域は解放されない
      {
        std::vector<int> v = {3, 1, 4};
        v.erase(v.begin());
    
        std::size_t cap = v.capacity();
        std::cout << cap << std::endl;
      }
    }
    

    出力例

    3
    3
    

    参照