To clear a vector in C++, call its clear() member function. It removes every element, destroys the elements, and leaves the vector with a size of zero. For example, values.clear(); is the usual way to empty a std::vector while keeping the vector available for reuse.
Clearing a vector does not necessarily release the memory it reserved. That distinction matters when you want to reuse a vector efficiently or reduce memory use. This guide explains how clear() works, when to use it, and what to do if you also want to request that the vector give up its allocated storage.
How to Clear a Vector in C++
Include the <vector> header, create a vector, and call clear() on it:
#include <iostream>
#include <vector>
int main() {
std::vector<int> values{10, 20, 30};
values.clear();
std::cout << values.size(); // Prints 0
}
After clear() returns, the vector contains no elements. Calling values.size() returns 0, and values.empty() returns true. You can still add new elements to the same vector afterward:
values.clear();
values.push_back(40);
There is no need to create a new vector just to remove the elements from an existing one. In most cases, clear() is the simplest and most readable solution.
What Does std::vector::clear() Do?
A vector manages a sequence of objects and storage for those objects. Calling clear() destroys all the elements currently in that sequence. If the vector contains class objects, their destructors are called. For built-in types such as int, there is no user-defined destructor to run.
After clearing, the vector’s size is zero. Its capacity, however, is not reduced by clear(). Capacity describes how many elements the vector can hold in its current allocation before it needs to request more storage. Keeping that storage can make a vector faster to refill, since it may avoid another allocation.
std::vector<int> numbers{1, 2, 3, 4};
std::size_t oldCapacity = numbers.capacity();
numbers.clear();
std::cout << numbers.size(); // 0
std::cout << numbers.capacity(); // Not reduced by clear()
The exact capacity is implementation-dependent, so programs should not rely on a particular number. The important point is that clear() empties the vector but does not request that its storage be released.
When to Use clear()
Use clear() when you want to remove the current elements but expect to keep using the vector. This is common in loops that process one batch of data at a time, in reusable buffers, or in containers that are repopulated repeatedly.
std::vector<int> batch;
for (int round = 0; round < 3; ++round) {
// Add items for this round.
batch.push_back(round * 10);
batch.push_back(round * 10 + 1);
// Process the items here.
batch.clear(); // Ready for the next round.
}
Because the vector can retain its capacity, the next batch may fit in the existing allocation. That can be useful in performance-sensitive code. If you are finished with the vector and want to reduce its memory footprint, consider one of the options below instead.
How to Clear a Vector and Request Memory Release
If you want to empty a vector and ask it to reduce its capacity, call clear() followed by shrink_to_fit():
std::vector<int> values{1, 2, 3, 4, 5};
values.clear();
values.shrink_to_fit();
shrink_to_fit() is a request, not a guarantee. The C++ standard allows the implementation to leave the capacity unchanged. Therefore, this approach is appropriate when reducing memory use is desirable but not essential to program correctness. Check capacity() afterward if you need to observe what happened, but do not make your program depend on the request being honored.
Another common technique is to swap the vector with an empty vector:
std::vector<int> values{1, 2, 3, 4, 5};
std::vector<int>{}.swap(values);
The temporary vector receives the contents and storage of values. When the temporary is destroyed at the end of the statement, its elements and allocation are released according to the vector’s allocator. This technique is often called the “swap with an empty vector” idiom.
For a vector with a custom allocator, take allocator compatibility into account before swapping. In ordinary code using the default allocator, the empty-vector swap is straightforward. Also remember that even when the vector releases its allocation, the underlying allocator or operating system may retain memory for reuse rather than immediately returning it to the system.
clear() Compared with Other Ways to Empty a Vector
There are several ways to remove elements from a vector, but they are not interchangeable in every situation:
-
clear()removes all elements and keeps the vector’s capacity. This is usually the best choice when you simply want an empty, reusable vector. -
resize(0)also reduces the vector’s size to zero. It is useful when a size is calculated dynamically, butclear()expresses the intention to remove everything more directly. -
erase(begin(), end())removes the full range of elements. It works, but is generally less clear than callingclear()when the whole vector is being emptied. -
shrink_to_fit()requests that unused capacity be reduced. It does not remove elements by itself, so callclear()first if you want an empty vector. - Swapping with an empty vector can release the vector’s current allocation, subject to allocator behavior and compatibility.
For example, values.resize(0); is valid, but a reader is more likely to recognize values.clear(); as the direct instruction to empty the container. Choose the method that most clearly communicates what your code should do.
Does clear() Delete Objects Pointed to by a Vector?
clear() destroys the elements stored in the vector, but it does not automatically delete separate objects that raw pointers refer to. If a vector stores pointers, clearing it removes the pointer values; it does not call delete on the objects they point to.
std::vector<Widget*> widgets;
// Assume widgets contains pointers created with new.
widgets.clear(); // Removes the pointers, not the Widget objects.
If those objects were allocated with new, failing to delete them can cause memory leaks. Modern C++ code should generally use smart pointers to express ownership:
#include <memory>
#include <vector>
std::vector<std::unique_ptr<Widget>> widgets;
// When widgets.clear() is called, its unique_ptr elements are
// destroyed, which also destroys the Widgets they own.
widgets.clear();
With std::unique_ptr, destroying each vector element also destroys the object it owns. With std::shared_ptr, the object is destroyed when the last owning shared pointer is destroyed. The key distinction is between removing a pointer from the vector and destroying the object the pointer refers to.
Iterator and Reference Invalidation
After you call clear(), do not use iterators, references, or pointers that referred to the vector’s former elements. Those elements have been destroyed, so access through such handles is invalid. Obtain new iterators or references only after adding new elements.
std::vector<int> values{10, 20, 30};
int* first = &values[0];
values.clear();
// Do not read or write through first here.
This rule applies even if the vector retains its capacity. Reserved storage may still exist, but the objects that occupied it no longer do. Storage capacity and the lifetime of the elements are separate concerns.
How Efficient Is clear()?
Clearing a vector takes time proportional to the number of elements because each element must be destroyed. For a vector of n elements, the operation is generally described as O(n). For simple types, the work may be very small, while objects with more involved destructors can require additional time.
If the vector will soon be filled with a similar number of elements, retaining its capacity can be beneficial. If it is large and will not be reused, asking to reduce its capacity may make sense. Avoid repeatedly shrinking and regrowing a vector in a performance-critical loop without measuring the effect: repeated allocations can cost more than keeping the storage available.
Common Mistakes When Clearing a Vector
-
Assuming capacity becomes zero:
clear()sets the size to zero but does not reduce capacity. - Assuming raw pointers are deleted: Clearing a vector of raw pointers removes the pointer elements but does not destroy the pointed-to objects.
- Using old iterators afterward: Iterators and references to the removed elements are no longer valid.
- Expecting shrink_to_fit() to guarantee release: It is a non-binding request, so capacity may remain unchanged.
- Clearing when assignment is intended: If you want to replace the contents with another sequence, assignment may communicate that goal more clearly.
These details help prevent memory-management bugs and make it easier to choose between reusing a vector and discarding its storage.
Conclusion
To clear a vector in C++, call myVector.clear(). This removes and destroys all its elements, makes its size zero, and leaves the vector ready for reuse. It does not reduce capacity, so the vector may keep its allocated storage for future elements.
If you also want to reduce the vector’s capacity, call shrink_to_fit() after clearing, while remembering that the request is not guaranteed. Swapping with an empty vector is another common way to discard the vector’s current storage, subject to allocator behavior. For most everyday cases, however, clear() is the simple, idiomatic answer to “How do I clear a vector in C++?”
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.