Use reserve to avoid unnecessary Memory Allocation
- When you know exactly or approximately how many elements will eventually appear in the container
vector int V; // if you do not need to use reserve to allocate memory first, the following cycle will re-allocate the memory multiple times (involving expensive actions such as allocation, recycling, copying, and destructor) v. reserve ( 1000 ); for ( int I = 1 ; I <= 1000 ; ++ I) {v. push_back (I) ;}
- Keep the maximum space you may need, and then, once you add full data, trim any excess capacity (you can consider
Use swap to Trim excess capacity
Method)
InSize and capacityThe relationship between them allows us to predict when insertion will cause the vector or string to be re-allocated.
StringS ;...If(S. Size () <S. Capacity ()){// Push_back will not invalidate the iterator, pointer, or reference pointing to this string, because the size of the string must be greater than its size.S. push_back ('X');}
Valid STL: use reserve to avoid unnecessary Memory Allocation