Let's look at the two usages of the resize () function in C + + Primer:
1, resize (n)
Adjusts the length of the container so that it can hold n elements.
If n is less than the current size of the container, the extra element is removed.
Otherwise, the element with the value initialization is added.
2, resize (n,t)
One more parameter T, which initializes all newly added elements to T.
And the use of Reserver () has only one
Reserve (N)
Pre-allocates storage space for n elements.
To understand the difference between these two functions, it is first to clarify the difference between the capacity (capacity) of the container and the size (length).
Size refers to the number of elements currently owned by the container;
Capacity, however, refers to the total number of elements that a container can store before it must allocate new storage space.
It can also be said to be the size of the pre-allocated storage space.
The resize () function is closely related to the size of the container. When resize (n) is called, the container's size is n.
Whether the capacity is affected depends on whether the resized container's size is greater than capacity.
The reserve () function is closely related to the capacity of the container.
After calling reserve (N), if the container's capacity<n, the memory space is redistributed, so that capacity equals N.
What if capacity>=n? Capacity no change.
From the use of the two functions can be found that the container calls the resize () function, all the space has been initialized, so it can be directly accessed.
The reserve () function pre-allocates space is not initialized, so it is inaccessible.