STL in Vector / map Notes

vector improve efficiency considerations and techniques

Vector STL is the most commonly used container than a user-defined array, having memory allocation transparent to the user, and so can grow dynamically.
vector what actions lead to inefficiency?

There is no doubt that when the vector is insufficient space reserved for
common actions push_back () function detects whether the space reserved enough at each element is inserted
when push_back () to reserve space is not enough: To re-allocate memory and copy currently it has all the elements to a new memory area. If you already have a lot of elements, this operation will become very expensive.

Vector memory management strategy is: once the space is insufficient, doubling the amount of data is large, this may be one to be reckoned with resources
so it should be avoided vector reallocate memory.
How to avoid the vector automatically re-allocate memory?

The number of elements can be estimated in advance, with reserved space allocated reserve function
this function allocates a specified amount of space, but does not perform any initialization, so it does not include the space allocated elements, it can not be accessed. Then use the push_back function the same way, this time before the reserve do not exceed space, vector memory will not be reallocated, but simply put back in order.

Published 18 original articles · won praise 0 · Views 5618

Guess you like

Origin blog.csdn.net/M_ZONE125/article/details/104881627