When is memory allocated for a vector?

Greetings,

I have a short question. If I simply declare a std::vector of N doubles, i.e.
 
  std::vector <double> (N);
,

when will the memory of N doubles be allocated? Right at this point, or only if I fill this vector with actual double values?


Yes, this does it on creation. you can use to N-1 via [] access right away.
> only if I fill this vector with actual double values?

On construction, the vector is filled with N zero initialised values of type double
You can also construct a sized vector with a value other than the default.

std::vector<double>(N, 5.3);

This creates a vector with N elements all initialized to 5.3.
http://www.cplusplus.com/reference/vector/vector/vector/
Thanks everyone!
It's interesting to consider what happens when you add a bunch of values to a vector. You probably know that it doesn't allocate new space for the items 1 at a time. That would be really inefficient. Instead it doesn't does* something like adding 50% more space when it needs it. You can see the extra space with the capacity() method.

When it allocates that (hypothetical) 50%, it does NOT create items in the new space. That would be inefficient. Instead, when you add a new item, it constructs the new item in the appropriate location in the buffer.

* Thank you seeplus for the PM reporting my blunder.
Last edited on
Topic archived. No new replies allowed.