Frees old memory.
The reserve member function allows you to minimize the number of times you allocate again, thus avoiding the overhead of allocating memory and pointer / iterator / reference failures again. Before explaining How reserve can do that. I'll briefly summarize the 4 member functions that are interrelated but sometimes confused. In a standard container, only the vector and string provide all 4 of these functions:
size () shows how many elements are in a container. It does not tell you how much memory the container allocates for the elements it includes.
capacity () shows how many elements can be accommodated by a container using the allocated memory.
This is the total number of elements that the container can hold. Instead of how many elements it can hold.
Suppose you want to know how much of a vector is used memory, you have to subtract size ()from Capacity ( ). Assume that size and capacity return the same value. It means there is no more space left in the container.
Resize (container::size_type N) forces the container to change to a state that includes n elements.
After calling resize ,size returns n.
Assuming that N is smaller than the current size, the elements at the end of the container will be refactored out. Assume that N is larger than the current size. The new element created by the default constructor is added to the end of the container. Assuming that N is larger than the current capacity, memory will be allocated again before the element is added.
Reserve (container::size_type N) forces the container to change its capacity to at least N. The premise is that n is not less than the current size. This typically results in another allocation, since the capacity is added. (assuming that n is smaller than the current capacity, the vector ignores the call.) Do nothing, while a string may reduce its capacity to the maximum of size () and n , but the size of the string must remain the same. )
For example, suppose you want to create a vector<int>that includes a value between 1 and.
Assume that the reserve is not used. You might do this:
Vector<int> v;
for (int i = 1;i <= 1000;++i)
V.push_back (i);
The loop will cause 2 to ten times to be allocated in the process. Assume that you use the reserve, as seen in the following:
Vector<int> v;
V.reserve (1000);
for (int i = 1;i <= 1000;++i)
V.push_back (i);
No more allocations will occur during the loop.