Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the capacity of an empty vector?

Tags:

c++

stl

vector

Looks like a stupid question. But comment to my answer to one of the SO question made me to think again.

[ comment says, capacity need not be zero for empty vector]

By default my answer would be 0 as there are no elements inside vector. It makes sense to keep the capacity as 0 and on the first allocation it can be increased without any performance hits.

But standard does not say anything one this. ( I checked in Josuttis book as well).

Is it purely implementation specific? Does any STL vendor use some arbitrary number as capcity for the empty vector?

Any thoughts...

like image 606
aJ. Avatar asked Nov 24 '09 05:11

aJ.


People also ask

What is capacity of empty vector?

By default my answer would be 0 as there are no elements inside vector. It makes sense to keep the capacity as 0 and on the first allocation it can be increased without any performance hits.

What is the capacity of a vector?

The capacity of a vector represents the maximum number of elements the vector can hold.

What does it mean for a vector to be empty?

std::vector::empty Returns whether the vector is empty (i.e. whether its size is 0). This function does not modify the container in any way. To clear the content of a vector, see vector::clear.

How big is an empty vector C++?

If the vector container is empty what will size() and empty() returns? Size will return 0 and empty will return 1 because if there is no element in the vector the size of that vector will be 0 and empty will be true so it will return 1.


2 Answers

C++ Standard 23.2.4.2 only says that vector::capacity is

The total number of elements that the vector can hold without requiring reallocation.

That means that the actual value is fully implementation specific.

like image 132
Kirill V. Lyadvinsky Avatar answered Oct 09 '22 03:10

Kirill V. Lyadvinsky


The capacity can be whatever the implementors feel is correct or necessary.

It should also be noted it's never "safe" to assume you know the current capacity() without a call to that function. If you reserve 10 elements, the implementor is of free to allocate one hundred if it so wants to. Or 11, 42 (preferred) or just 10.

like image 44
GManNickG Avatar answered Oct 09 '22 03:10

GManNickG