Release old memory.
The reserve member function allows you to minimize the number of reallocation times, thus avoiding overhead caused by memory reallocation and pointer/iterator/reference invalidation. Before explaining how reserve can do this, I will briefly summarize four member functions that are correlated but sometimes obfuscated. In a standard container, only vector and string provide all the four functions:
Size () indicates the number of elements in the modified container. It does not tell you how much memory the container allocates to its own elements.
Capacity () indicates how many elements the container can accommodate using the allocated memory. This is the total number of elements a container can accommodate, rather than the number of elements it can accommodate. If you want to know how much memory a vector uses, You have to subtract size () from capacity (). If size and capacity return the same value, it means there is no space left in the container.
Resize (container: size_type N) forces the container to change to a State that contains n elements. After Resize is called, size returns n. If n is smaller than the current size, the elements at the end of the container will be destructed. If n is greater than the current size, the new elements created by the default constructor are added to the end of the container. If n is larger than the current capacity, the memory will be re-allocated before the element is added.
Reserve (container: size_type N) forces the container to change its capacity to at least N, provided that N is not smaller than the current size. This usually leads to reallocation because the capacity increases. (If n is smaller than the current capacity, the vector ignores this call and does nothing. String may reduce its capacity to the maximum value in size () and n, but the size of the string must remain unchanged .)
For example, assume that you want to create a vector containing values between 1 and 1000 <int>. If reserve is not used, you may do the following:
Vector <int> V;
For (INT I = 1; I <= 1000; ++ I)
V. push_back (I );
This cycle will result in two to ten reallocation. If you use reserve, as shown below:
Vector <int> V;
V. Reserve (1000 );
For (INT I = 1; I <= 1000; ++ I)
V. push_back (I );
Then, the re-allocation will not occur during the loop process.