C ++ std :: vector clear all elements

Consider a std::vector :

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

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

+7
c ++ c ++ 11 stdvector
source share
2 answers

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

vec = std::vector<int>() calls the assignment operator copy / move (Since C ++ 11), this replaces the contents of vec with the contents of other . other in this case is the newly constructed empty vector<int> , which means that it has the same effect as vec.clear(); . The only difference is that clear() does not affect the throughput of the vector when reassigned, it resets it.

Old elements are freed properly as with clear() .

Note that vec.clear() always as fast and without an optimizer executing it, most likely faster than creating a new vector and assigning it vec .

+8
source share

They are different:

clear guaranteed not to change capacity.

When transferring an assignment, a change in capacity to zero is not guaranteed, but it can and will be in a typical implementation.


The clear guarantee is based on the following rule:

During insertions that occur after the reserve() call, redistribution does not occur until the insertion makes the vector size larger than the capacity() value

Clear message conditions:

Erases all items in a container. Message: a.empty() returns true

Assignment Message Status:

a = rv;

a must be equal to rv value before this

a = il;

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

+4
source share

All Articles