myVector.reserve(n)
just tells the vector to allocate enough storage for n
elements, so that when you push_back
new elements into the vector, the vector won't have to continually reallocate more storage -- it may have to do this more than once, because it doesn't know in advance how many elements you will insert. In other words you're helping out the vector implementation by telling it something it wouldn't otherwise know, and allowing it to be more efficient.
But reserve doesn't actually make the vector be n
long. The vector is empty, and in fact statements like myVector[0] = something
are illegal, because the vector is of size 0: on my implementation I get an assertion failure, "vector subscript out of range". This is on Visual C++ 2012, but I think that gcc is similar.
To create a vector of the required length simply do
vector<Foo> myVector(n);
and forget about the reserve
.
(As noted in the comment you an also call resize
to set the vector size, but in your case it's simpler to pass the size as the constructor parameter.)