Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++: Empty a vector for real

📅 2012-Apr-30 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ clear, cpp, vector ⬩ 📚 Archive

clear() is the method used to empty a STL vector in C++. However, it merely sets the size of the vector to zero. In almost all STL implementations, the vector is still consuming the same amount of memory it was before the call to clear(). This can be seen by calling the capacity() method, which returns the actual number of items which the vector can hold without needing or reallocating any new memory.

#include <iostream>
#include <vector>
int main()
{
    vector< int > v( 1000000 );
    v.clear();
    std::cout << v.capacity() << std::endl; // 1000000
    return 0;
}

But, there will be situations where memory is tight and you would like to actually clear a vector of all its memory. This can be achieved using the shrink_to_fit() method, which was introduced in C++11:

v.clear();
v.shrink_to_fit(); // Capacity of v is now 0

If you are using an old C++ compiler or STL implementation that does not support shrink_to_fit(), there is another trick to empty a vector: swap its contents with a vector that is actually empty:

vector< int >().swap( v ); // Capacity of v is now 0

Our original vector now points to the (empty) space of the new vector. The new vector now points to the capacity of the old vector. But, the lifetime of the new vector is the scope of this statement. As soon as that scope ends, the new vector is deleted, thus freeing the memory occupied by the old vector.

Tried with: Visual C++ 2010


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧