VECOTR is a dynamic array, as the name implies, he can dynamically increase his own length.
Memory mechanism:
But how to increase their length?
Vector has two functions one is capacity () returns the memory space that is the size of the buffer, and the other is the number of the number in the current array that the size () returns. Vector add element, when the capacity has not been put into the data, then he will re-apply for a piece of memory, the previous memory using the copy constructor copy to the new memory, and then put the newly added content in the back, and at this time he applied for memory space is twice times the original space, I measured twice times
Release of Buffer
The memory occupied by Vecotor only increases, erase only clears the value of a certain interval (Earse (Arr.begin (), Arr.end ()) or clears a value (erase (x)), but it is unchanged for memory space.
All memory space is retrieved by the system at the time of the vector's destruction. Empty () is used to detect if the container is empty, and clear () clears all elements. However, even if clear (), the vector occupies a memory space that remains the same, unable to guarantee the recovery of memory.
method One: Vecotr<Type> (). Swap (arr)//Reclaim arr Memorymethod Two: templates: Template<classT >voidClearvector (vector< T >&VT) {Vector< T >vttemp; Vetemp.swap (VT);} Calling a template functionvoidclearvector<vector< T> &VT) {Vector<int> temp;//The temporary object is not initialized with a buffer size of 0 and no dataArr.swap (temp);//To Exchange data with our object, arr's buffer is gone. }//temporary variables are refactored, and temp calls the vector destructor to free up space
----------------------------------------------------------------------------
Performance Analysis:
The main comparison is three kinds of insertion methods:
1, Direct push_back () 2, reserve (n) predetermined n space, of course, subsequent push_back () will increase, where the value is not determined, 3 resize (n, x) to apply n space initialized to X,
Reserve only maintains a minimum space size, while resize is a buffer redistribution, which involves more judgment and memory processing so slower than reserve, for the number of data can be determined, the first preset space size is necessary. Direct push_back data is time-consuming to move frequently
Memory mechanism and performance analysis of vector in C + + STL