This post will discuss how to delete the vector’s contents and free up the memory allocated by the vector to store objects in C++.

1. Using vector::clear function

We can use the vector::clear function to remove all elements from the vector. It works by calling a destructor on each vector object, but the underlying storage is not released. So, we’re left with a vector of size 0 but some finite capacity.

 

 

Download  Run Code

Output:

The vector size is 0, and its capacity is 5

 
Starting with C++11, we can call the vector::shrink_to_fit function after clear(), which reduces the vector’s capacity to fir the size. It works by “requesting” a reallocation on the vector.

 

 

Download  Run Code

Output:

The vector size is 0, and its capacity is 0

2. Using vector::erase function

Another solution is to call the vector::erase function on the vector, as shown below. This also suffers from the same problem as the clear() function, i.e., reallocation of memory is not guaranteed to happen on the vector.

 

 

Download  Run Code

Output:

The vector size is 0, and its capacity is 0

3. Using vector::resize function

We can also use the vector::resize function for resizing the vector. Notice that this function does not destroy the vector objects, and all references to objects remain valid.

 

 

Download  Run Code

Output:

The vector size is 0, and its capacity is 0

4. Using vector::swap function

All the above solutions fail to release the memory allocated to the vector object without calling the vector::shrink_to_fit function. The shrink_to_fit() shrinks the capacity to fit the size, but we can’t entirely rely on it. This is because it makes a non-binding request, and the vector implementation is free to ignore it completely.

There is another workaround to free the memory taken by the vector object. The idea is to swap the vector with an empty vector (with no memory allocated). This will de-allocate the memory taken by the vector and is always guaranteed to work.

 

 

Download  Run Code

Output:

The vector size is 0, and its capacity is 0

That’s all about deleting vector contents and free up memory in C++.