6

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...

Community
  • 1
  • 1
aJ.
  • 34,624
  • 22
  • 86
  • 128

4 Answers4

16

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.

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
7

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.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • 2
    Indeed. GNU STL starts with a capacity of 0. The Java API spec says it starts with a capacity of 10. It's really an implementation detail. – Josh Lee Nov 24 '09 at 05:31
0

For a quick scan of Google and bouncing off a few random forums (of generally unknown pedigree, so, yeah), it appears to be implementation specific.

Pretty much a non-issue since you can immediately change it with a call to reserve.

Donnie
  • 45,732
  • 10
  • 64
  • 86
-1

One can change capacity of vector by using resize() API on vector if one is sure of what data vector is going to store and that is implementation specific.

Vivek
  • 473
  • 1
  • 3
  • 10
  • 1
    > One can change capacity of vector by using resize() No, that also changes the size. reserve changes the capacity without affecting the size. – Fred Nov 24 '09 at 12:02
  • Yup fred you are right reserves only changes capacity without affecting size of vector. apologies. – Vivek Nov 25 '09 at 06:13
  • More precisely, The capacity of a vector<> can be resized by calling either reserve() or resize(). These member functions differ in two respects. Unlike resize(), which allocates memory and initializes it with a default value, reserve() only allocates raw memory without initialization. In addition, reserve() does not change the size of a vector; it only changes the vector's capacity. – Vivek Nov 25 '09 at 06:18