Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::vector clear all elements

Consider a std::vector:

std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);

Would vec.clear() and vec = std::vector<int>() do the same job? What about the deallocation in second case?

like image 381
Arun KS Avatar asked Aug 22 '17 09:08

Arun KS


2 Answers

vec.clear() clears all elements from the vector, leaving you with a guarantee of vec.size() == 0.

vec = std::vector<int>() calls the copy/move(Since C++11) assignment operator , this replaces the contents of vec with that of other. other in this case is a newly constructed empty vector<int> which means that it's the same effect as vec.clear();. The only difference is that clear() doesn't affect the vector's capacity while re-assigning does, it resets it.

The old elements are deallocated properly just as they would with clear().

Note that vec.clear() is always as fast and without the optimizer doing it's work most likely faster than constructing a new vector and assigning it to vec.

like image 185
Hatted Rooster Avatar answered Oct 18 '22 20:10

Hatted Rooster


They are different:

clear is guaranteed to not change capacity.

Move assignment is not guaranteed to change capacity to zero, but it may and will in a typical implementation.


The clear guarantee is by this rule:

No reallocation shall take place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity()

Post conditions of clear:

Erases all elements in the container. Post: a.empty() returns true

Post condition of assignment:

a = rv;

a shall be equal to the value that rv had before this assignment

a = il;

Assigns the range [il.begin(),il.end()) into a. All existing elements of a are either assigned to or destroyed.

like image 31
eerorika Avatar answered Oct 18 '22 20:10

eerorika