-1

I have vector v, initial size = 10. pushed 10 element. while adding 11th element, it will dynamic grow the size (N = N*2) i.e. 20 element. Now vector has 11 element and can accommodate 20 element.

My question is if we delete a element from vector will any point vector capacity decreases from N = N/2 something just as it increase by N*2.if yes then what is strategy behind the deallocation of vector or shrinking. because as per above example if we delete 11th element it will shrink to 10 and again if we add 11th it will grow. if i keep adding and deleting 11th element it will keep allocating and allocate memory which is not good.

EDIT : if answer is no then for eg. 1000 element is added into vector and now 990 element has been popped out still it use space for 1000 element. Will it not be waste of memory?

Suri
  • 3,287
  • 9
  • 45
  • 75
  • 1
    Please format your question. Formatting help is visible as you write the question, [and here](http://stackoverflow.com/editing-help). From the looks of past posts, I'm actually in awe of how you managed to get 1k rep without formatting anything (as far as I can find). – chris Apr 11 '15 at 19:31
  • Don't indent paragraphs. The software _here_ interprets enough indentation as something special... and even if it didn't, indentation usually doesn't show up on the internet anyways. –  Apr 11 '15 at 19:39
  • sorry . Now formatted. – Suri Apr 11 '15 at 19:39
  • `erase` or similar methods do not ever decrease vector capacity. Only things like `shrink_to_fit` or `swap` may. – Igor Tandetnik Apr 11 '15 at 19:41

1 Answers1

1

The vector doesn't shrink, unless you tell it to shrink by calling .shrink_to_fit(). (even here, the request is non-binding)

milleniumbug
  • 15,379
  • 3
  • 47
  • 71
  • eg. 1000 element is added into vector and now 990 element has been popped out still it use space for 1000 element. Will it not be waste of memory? – Suri Apr 11 '15 at 19:44
  • 1
    @Suri Well, it does exactly that. Memory management is complicated, and the other option (shrinking by default) would be IMHO much worse (it saves memory by default, but you can't control how much time it takes, also you can't control the iterator invalidation). – milleniumbug Apr 11 '15 at 19:49