The standard indicate in which situation an iterator is invalidated. You need to read good documentation preferably before using STL containers and remember the rules. Once you know the rules, you should be able to know hot to write correct code.
Simplified rules would be that insert/remove invalidate iterators for vector/deque.
Ignoring errors (missing elements, empty list...), following code should works:
auto iter = find(a.begin(), a.end(), 2);
auto it_erase = iter;
++it_erase;
a.erase(it_erase);
a.insert(iter, 8);
for(itr = a.begin(); itr != a.end(); ++itr)
{
cout << *itr << endl;
}
return 0;
By the way, it is not hard to find information using Google:
vector::erase - C++ Reference[
^]
If deletion must be done after insertion (depending on how you want code to behave if an exception is thrown while inserting an item),
insert
will returns an iterator positioned at the first inserted element.
Thus something like this should do:
auto it_erase = a.insert(iter, 8) + 1; a.erase(it_erase);
I am not sure if it should be +1 or +2 as your code being invalid and expected result not indicated in the question...
If you use +1, you would get:
4 5 8 9 6
If you use +2, you would get:
4 5 8 2 6
If existing code has proper behavior, then
+1
would be appropriate. If the same code with list give the desired result, then +2 should be used. This is not clear from the question...
By the way, if you are using Visual Studio and compiling the
DEBUG
version, it probably tells you that you are using an invalidated iterator.
Rules are well defined since at least 20 years ago as I have one book from 1996 and this is documented in it.