"C++ Primer" reading notes-Chapter 04 vector object growth

Author: Ma Zhifeng
link: https: //zhuanlan.zhihu.com/p/24455625
Source: know almost
copyrighted by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

statement:

  • The content in the article is collected and compiled from "C++ Primer Chinese Edition (5th Edition)", and the copyright belongs to the original book.
  • The original book has more detailed and wonderful interpretations, please buy genuine books for learning.
  • This article is only for learning and communication, any form of reprinting is prohibited

text

In order to support fast random access, the elements in the vector are stored continuously (contiguous memory space)

As mentioned earlier, adding elements to the vector may cause the reallocation of the entire container memory space

In order to reduce the number of re-allocations of container space, every time a new memory space has to be acquired, a larger memory space (2 times?) than the actual demand is allocated.

This strategy ensures that the expansion operation of vector is usually faster than list and deque

Management container

c.shrink_to_fit()  
c.capacity()  
c.reserve( n )

capacity How many elements can be saved without reallocating the memory space. Reserve allocates memory space that can hold
at least n elements.
shrink_to_fit() Request to reduce capacity to the same size as size, but the request may be ignored, depending on the specific implementation

reserve(n), if n is less than the actual capacity, do nothing, reserve will not reduce the memory space occupied by the
container. resize only changes the number of elements in the container, not the capacity of the container

shrink_to_fit only applies to vector, string and deque

capacity and reserve only apply to vector and string

Guess you like

Origin blog.csdn.net/qq_26751117/article/details/53821788