0
int a[] = {1,2,3,4};
vector<int>  v(a, a + sizeof(a) / sizeof(int) ); // v:1 2 3 4
for(vector<int>::iterator it = v.begin(); it != v.end(); ++it) {
    if (*it == 2)
        v.insert(v.begin(), 0); // v:0 1 2 3 4
}

The question is after the insertion, does it still point to 2? or change to 1? or anything else? I got a really weird output and couldn't figure out.

Thank you!

Jacob
  • 43
  • 8
  • 2
    you may be interested in [iterator invalidation rules](http://stackoverflow.com/questions/6438086/iterator-invalidation-rules) – jaggedSpire Aug 22 '16 at 17:40
  • 1
    Well modifying the vector changes also the iterator so iterating through it is no longer possible, because elements like `v.begin()` and `v.end()` loose consistency and I guess get deallocated... – DIEGO CARRASCAL Aug 22 '16 at 17:47
  • In this case, iterating isn't possible because all iterator after the insertion point are invalidated. The iterators before are still valid but you insert a first element so there is no chance. – Gustavo Aug 22 '16 at 21:36

0 Answers0