Internally working of vector??

vectorv(5);

Is this the way the, vector will work when the 6th element will come:

  1. Allocate the new space of size 6
  2. Copy all the elements to the newly allocated space.
  3. Free the previously allocated space.

I would really advice you to google your questions, as STL is a well documented library, you might find your answer there itself.
Anyway yes the process you mentioned occurs only when the vector runs out of it’s buffer capacity. This link might help you.

@virresh
It mean’s vectors are very inefficient, when we do not know size in advance.

@arpit728 not in practice. The resize done is typically to get twice the current size and thus not every time we push. This situation might arise once in a while or when the type of object of which the vector is made of is too large (copy operation is costly) but you can safely take the cost of insertion as O(1) operation by ammortized analysis. See this link for complete analysis :

So in conclusion vectors aren’t that inefficient. They will almost never be the reason for a TLE on a question.

@virresh

Nice explanation, thank you.