![]() |
VOOZH | about |
In C++, you can delete all items from a vector to either clear its contents or free its memory. In this article, we will learn how to delete all items from a vector in C++.
The recommended way to delete all items from a vector is by using the vector clear() function. Let’s take a look at a simple example:
0
Explanation: The vector clear() function removes all elements from the vector, reducing its size to zero.
Note: Although clear() removes all elements, the vector's capacity (memory allocation) remains unchanged. To reduce memory usage, use shrink_to_fit() after clearing.
C++ provides a few more methods to delete all the elements and clear the vector. Some of them are as follows:
The vector erase() function can remove all elements from a vector by specifying the range [begin, end).
0
Explanation: Using the range as v.begin() and v.end() removes all elements.
Swap the vector with an empty vector using vector swap() method to delete all elements and reset its capacity.
0
Instead of swapping, a vector can also be assigned an empty vector using vector assign() or simply = operator to delete all the elements. This method also clears the capacity.
0
The vector resize()method can increase or decrease the size of vector, so to clear all elements of vector we can decrease its size to 0 using resize().
0