size of vector when created?

Hi, When a vector is created is it just a random size? or has the pointer to the heap just been established and it just points to one block of memory, and then when the vector gets filled it is reallocated.

I am asking because I am working on a problem, and I wanted to initalise the vector with an initial size since i knew the size, and didnt want to take up more memory. I know i can create the vector then fill it to the size i want with, for example zeros. But when i Just do vector<int> v. What is actually created and what is the size?
Do we really need to know, or does the standard leave that detail to implementers?

The vector has both size() and capacity(). If capacity is more than 0 for new, empty vector, then it has preallocated no space.

You can reserve:
std::vector<int> sample; // empty
sample.reserve(7); // still empty, but has allocated memory for 7 integers
sample.push_back(42); // has one element, can add 6 more before reallocation is necessary 
for array like behavior:
vector<int> sized(100); //100 locations ready to use:
sized[50] = 42; //ok, its there and ready to roll.

using push-back to grow to fit data is the last resort and worst option. use resize, reserve, or constructed size as much as possible.
if memory is a true concern and you are unsure of the sizes, you can also shrink to fit if necessary.
Last edited on
Topic archived. No new replies allowed.