kiryakov
kiryakov

Reputation: 145

With a 2D vector, does calling clear() on the 1st level clear all the memory associated with that vector?

I have a 2D vector declared as such:

vector<vector<uint16_t>> vector;

After this is used and I need to clear all memory associated with it, even the elements in the [][X] dimension, can I simply do:

vector.clear();

Or do I have to go through each of the vectors inside and call .clear() on them, before finally calling it on the main vector? If that is the case, what would be a clean solution for that?

Upvotes: 0

Views: 364

Answers (2)

jaswant.panchumarti
jaswant.panchumarti

Reputation: 568

With a 2D vector, does calling clear() on the 1st level clear all the memory associated with that vector?

Yes, clear erases all elements from the container.

Quoting from here,

std::vector<T,Allocator>::clear

After this call, size() returns zero. Invalidates any references, pointers, or iterators referring to contained elements. Any past-the-end iterators are also invalidated.

But this does not affect allocation/deallocation of internal storage in any way whatsoever. So, if you meant to ask,

With a 2D vector, does calling clear() on the 1st level FREE all the memory associated with that vector?

No. As per standard,

Leaves the capacity() of the vector unchanged (note: the standard's restriction on the changes to capacity is in the specification of vector::reserve, see 1)

So, if you wish to free up memory, either go for shrink_to_fit() or better swap contents with an empty vector. This is what most but not all implementations do.

v.swap(std::vector<T>());
v.swap(std::vector<std::vector<T>>()); // if vector of vectors

Upvotes: 1

orlp
orlp

Reputation: 118016

Since a vector neatly destructs its elements and deallocates the used memory when itself gets destructed, and v.clear() also destructs the elements in the vector, calling v.clear() is a perfectly valid way to delete an entire 2D vector.

Note that if you want also the memory for v itself cleaned up you need to call v.shrink_to_fit() after v.clear().

Upvotes: 3

Related Questions