Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling clear on a vector immediately after construction?

Tags:

c++

std

I've seen some C++ code like this:

std::vector<int> vec;
vec.clear();
vec.push_back(42);

What is the purpose (if any) of clearing the vector right after creating it?

like image 970
Joseph Kaptur Avatar asked Aug 28 '19 02:08

Joseph Kaptur


People also ask

Do we need to clear vector?

The vector (like all standard containers) owns the objects inside it. So it is responsible for destroying them. Note: If you vector contains pointers then it owns the pointers (not what the pointers point at). So these need to be deleted.

What does vector Clear () do?

vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.

Does vector clear change capacity?

The standard mandates that the capacity does not change with a clear as reserve guarantees that further adding of elements do not relocate until the requested capacity is reached. This directly enforces clear to not reduce the capacity.

How do you clear a std vector?

The C++ function std::vector::clear() destroys the vector by removing all elements from the vector and sets size of vector to zero.


1 Answers

It serves no purpose - the vector is already created in an empty state.

If you are lucky, your compiler will optimize away this redundant call entirely - recent versions of both gcc and clang do exactly that.

like image 100
BeeOnRope Avatar answered Sep 24 '22 01:09

BeeOnRope