Friday, July 30, 2010

Invalidating Iterators

A call to push_back() on a vector can invalidate all of it's iterators.

If the vector's capacity is reached, then a reallocation occurs. All of the elements will be copied to the new location, and deleted from the old location. Reallocations typically increase the capacity from 1.5 to 2 times. You can tell what the capacity is by calling the member function, capacity(). You can set the capacity by calling the member function reserve(). You see how much capacity you have left by calculating v.capacity() - v.size(). You can call resize() to increase or decrease the size. You can increase the memory footprint of the vector with resize, but you cannot decrease the memory footprint with resize(). If you want to do this, you can use the "Swap Trick", where you copy the elements to a newly created empty vector, then call swap() on the old and new vectors.

Reference: The C++ Standard Library: A Tutorial and Reference by Nicolai M. Josuttis. Addison-Wesley, 1999, p. 241.

No comments:

Post a Comment