Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::vector<T,Allocator>::reserve

      From cppreference.com
      <cpp‎ |container‎ |vector
       
       
       
      std::vector
      Member types
      Member functions
      Non-member functions
      (until C++20)(until C++20)(until C++20)(until C++20)(until C++20)
      Deduction guides(C++17)
       
      void reserve( size_type new_cap);
      (constexpr since C++20)

      Increase the capacity of the vector (the total number of elements that the vector can hold without requiring reallocation) to a value that's greater or equal tonew_cap. Ifnew_cap is greater than the currentcapacity(), new storage is allocated, otherwise the function does nothing.

      reserve() does not change the size of the vector.

      Ifnew_cap is greater thancapacity(), all iterators (including theend() iterator) and all references to the elements are invalidated. Otherwise, no iterators or references are invalidated.

      After a call toreserve(), insertions will not trigger reallocation unless the insertion would make the size of the vector greater than the value ofcapacity().

      Contents

      [edit]Parameters

      new_cap - new capacity of the vector, in number of elements
      Type requirements
      -
      T must meet the requirements ofMoveInsertable into*this.(since C++11)

      [edit]Return value

      (none)

      [edit]Exceptions

      If an exception is thrown, this function has no effect (strong exception guarantee).

      IfT's move constructor is notnoexcept and T is notCopyInsertable into*this, vector will use the throwing move constructor. If it throws, the guarantee is waived and the effects are unspecified.

      (since C++11)

      [edit]Complexity

      At most linear in thesize() of the container.

      [edit]Notes

      Correctly usingreserve() can prevent unnecessary reallocations, but inappropriate uses ofreserve() (for instance, calling it before everypush_back() call) may actually increase the number of reallocations (by causing the capacity to grow linearly rather than exponentially) and result in increased computational complexity and decreased performance. For example, a function that receives an arbitrary vector by reference and appends elements to it should usuallynot callreserve() on the vector, since it does not know of the vector's usage characteristics.

      When inserting a range, the range version ofinsert() is generally preferable as it preserves the correct capacity growth behavior, unlikereserve() followed by a series ofpush_back()s.

      reserve() cannot be used to reduce the capacity of the container; to that endshrink_to_fit() is provided.

      [edit]Example

      Run this code
      #include <cstddef>#include <iostream>#include <new>#include <vector> // minimal C++11 allocator with debug outputtemplate<class Tp>struct NAlloc{typedef Tp value_type;     NAlloc()=default;template<class T>    NAlloc(const NAlloc<T>&){}     Tp* allocate(std::size_t n){        n*= sizeof(Tp);        Tp* p=static_cast<Tp*>(::operator new(n));std::cout<<"allocating "<< n<<" bytes @ "<< p<<'\n';return p;} void deallocate(Tp* p,std::size_t n){std::cout<<"deallocating "<< n* sizeof*p<<" bytes @ "<< p<<"\n\n";::operator delete(p);}}; template<class T,class U>bool operator==(const NAlloc<T>&,const NAlloc<U>&){returntrue;} template<class T,class U>bool operator!=(const NAlloc<T>&,const NAlloc<U>&){returnfalse;} int main(){constexprint max_elements=32; std::cout<<"using reserve:\n";{std::vector<int, NAlloc<int>> v1;        v1.reserve(max_elements);// reserves at least max_elements * sizeof(int) bytes for(int n=0; n< max_elements;++n)            v1.push_back(n);} std::cout<<"not using reserve:\n";{std::vector<int, NAlloc<int>> v1; for(int n=0; n< max_elements;++n){if(v1.size()== v1.capacity())std::cout<<"size() == capacity() == "<< v1.size()<<'\n';            v1.push_back(n);}}}

      Possible output:

      using reserve: allocating 128 bytes @ 0xa6f840deallocating 128 bytes @ 0xa6f840 not using reserve: size() == capacity() == 0allocating 4 bytes @ 0xa6f840 size() == capacity() == 1allocating 8 bytes @ 0xa6f860deallocating 4 bytes @ 0xa6f840 size() == capacity() == 2allocating 16 bytes @ 0xa6f840deallocating 8 bytes @ 0xa6f860 size() == capacity() == 4allocating 32 bytes @ 0xa6f880deallocating 16 bytes @ 0xa6f840 size() == capacity() == 8allocating 64 bytes @ 0xa6f8b0deallocating 32 bytes @ 0xa6f880 size() == capacity() == 16allocating 128 bytes @ 0xa6f900deallocating 64 bytes @ 0xa6f8b0 deallocating 128 bytes @ 0xa6f900

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 329C++98reallocation might be triggered if an insertion
      makes the size of the vector greater than the size
      specified in the most recent call toreserve()
      only triggers if the size
      of the vector becomes
      greater thancapacity()
      LWG 2033C++11T was not required to beMoveInsertablerequired

      [edit]See also

      returns the number of elements that can be held in currently allocated storage
      (public member function)[edit]
      returns the maximum possible number of elements
      (public member function)[edit]
      changes the number of elements stored
      (public member function)[edit]
      reduces memory usage by freeing unused memory
      (public member function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/container/vector/reserve&oldid=171517"

      [8]ページ先頭

      ©2009-2025 Movatter.jp