0

I have a vector like below

vector<unsigned int> myvector;
vector<unsigned int>::iterator it;

//fill it 
for (i=1; i<=10; i++) myvector.push_back(i);

//I want delete first one 
it = myvector.begin();
myvector.erase(it++);

//I want to know if I am in last element
if(it != myvector.end()) 
      cout << "a test";

but in compare expression my program crashes. why?

herzl shemuelian
  • 3,346
  • 8
  • 34
  • 49
  • 3
    This code doesn't compile. There is no `vector::insert` method that takes one argument. Please post the real code. – john Aug 07 '12 at 12:30

4 Answers4

6

Simply put, because after calling erase(), all iterators that point to the erased position or later positions in the vector are invalid. See, for example, here for official documentation of this.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
5

Because erase() invalidates the iterators at the and after the point of erasure.

OTOH, the return value is an iterator that points at the element after the erased one, so you can do it like this:

it = myvector.erase(it);
if (it == myvector.end()) { ... }
jrok
  • 54,456
  • 9
  • 109
  • 141
2

you should not ha to increment 'i' while erasing it since erase return the next valid iterator

I think that this probably answer your question

https://stackoverflow.com/a/4645727/623546

Community
  • 1
  • 1
MimiEAM
  • 2,505
  • 1
  • 26
  • 28
1

The iterators between the position of the erased element and the end of the vector are invalidated by erase(). See here.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480