CKTIS / C++
std::vector::clear — erase all elements without reducing capacity
`std::vector::clear` destroys all elements and sets the vector’s size to zero while keeping its capacity available for later insertions.
Version: ISO C++23; implementation support may vary
Syntax
#include <vector>
// Member declaration in std::vector<T, Allocator> (C++23):
constexpr void clear() noexcept;
// Call on a non-const vector v:
v.clear();std::vector::clear is a member function from <vector>: call v.clear() on a non-const vector. It takes no arguments and returns void. The call ends every element’s lifetime; afterward, v.size() == 0 and v.empty() is true, even if the vector was already empty. Complexity is linear in the number of elements before the call. The function has been noexcept since C++11 and constexpr since C++20.
Capacity (v.capacity()) stays unchanged. That does not keep the old elements alive: pointers, references, and iterators to them are invalidated. Do not reuse a saved end() iterator either; get fresh begin() and end() iterators when needed.
Use clear() when new results should replace old ones rather than be appended to them. If you are copying a prefix, make sure its source remains available after you clear the destination. clear() is not a secure memory wipe; shrink_to_fit() is a separate, non-binding request to reduce capacity.
Examples
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
const std::vector<std::string> ranked{"Ada", "Lin", "Mina"};
std::vector<std::string> names{"Old A", "Old B", "Old C"};
constexpr std::vector<std::string>::size_type k = 2;
const auto count = std::min(k, ranked.size());
const auto old_capacity = names.capacity();
names.clear();
std::cout << "size after clear: " << names.size() << '\n';
std::cout << "capacity unchanged: " << std::boolalpha
<< (names.capacity() == old_capacity) << '\n';
for (decltype(names)::size_type i = 0; i < count; ++i) {
names.push_back(ranked[i]);
}
std::cout << "replacement names:\n";
for (const auto& name : names) {
std::cout << name << '\n';
}
}Result
size after clear: 0 capacity unchanged: true replacement names: Ada Lin
The program caps `k` at the size of the separate source vector, clears `names`, and appends the selected prefix. It compares capacity before and after clearing without assuming a specific numeric value.
Related lessons
- C++ · Lesson 23 · Advanced · Version: 3