1

Will vector iterators be corrupted if you add elements to the vector?

AturSams
  • 7,568
  • 18
  • 64
  • 98
  • 2
    Yes, because there may be reallocation. – Arkady Jan 26 '16 at 12:34
  • I have not noticed that the documentation say something that would ensure that you can use the iterator after changing the vector. I do not think that there is any guarantee, even if the data is not reallocated. – JojOatXGME Jan 26 '16 at 12:39
  • 1
    "all iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated) [23.3.6.5/1]" – Dan Jan 26 '16 at 12:40
  • 3
    Is reading documentation not a thing people do anymore? – juanchopanza Jan 26 '16 at 12:45
  • @Dan Do you have the source of this quote? Is it a guarantee or the behavior in practice? (EDIT: I have found the reference by myself right now. You can find it in the link posted by Dan before) – JojOatXGME Jan 26 '16 at 12:45
  • @Dan While it's clear that the answer to `A` includes the answer to `B` it does not mean that question `a` == `b`. My question is very specific (the wording and intention is different). A question is not just a room to put information in. It has it's own specific intentions and goals. For instance, in my case an answer explaining how to avoid this (by using indices for instance) would be more appropriate where in the other question, it would be an awkward fit. – AturSams Jan 26 '16 at 12:54

2 Answers2

4

Yes.

Adding elements to a vector can cause reallocation, which will invalidate all iterators and pointers to the vector elements.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • This was my guess so if you use indices you are completely safe. – AturSams Jan 26 '16 at 12:52
  • @zehelvion Yes, indices will never change by this. – Some programmer dude Jan 26 '16 at 12:55
  • Could you add that and any alternative that comes to mind to the answer? My main goal was to make sure I'm going to avoid this pitfall. The reason it is very *annoying* to fledglings is that it will probably appear to work as expected and then suddenly do something odd on occasion (undefined behavior). – AturSams Jan 26 '16 at 12:57
4

Yes, this can happen. If the vector resizes old iterators are no longer valid. This is not true for all collections.

Take a look at the invalidation rules.

Johannes
  • 6,490
  • 10
  • 59
  • 108