hovnatan
hovnatan

Reputation: 1385

How to remove all elements from a vector

Why doesn't this code remove all the elements from a vector? Thanks!

for (int i = 0; i < vec.size(); i++)
  vec.erase(vec.begin());

Upvotes: 0

Views: 371

Answers (2)

fredoverflow
fredoverflow

Reputation: 263350

If you want to make sure that all memory is released immediately, there is an established idiom:

std::vector<YourTypeHere>().swap(vec);

This creates a temporary vector which is initially empty, swaps its contents with your vector, and then the temporary dies at the semicolon.

Upvotes: 0

Marcelo Cantos
Marcelo Cantos

Reputation: 186098

Because i and vec.size() cross paths at about half the original vector size. You can simply write while (!vec.empty()) ….

Note that clearing a vector by repeatedly removing the first element takes O(n2) time (vec.clear() takes O(1) unless the elements have a non-trivial destructor, in which case it takes O(n)).

Unless you're doing this for fun, use vec.clear().

Upvotes: 6

Related Questions