views:

159

answers:

1

Using http://www.cppreference.com/wiki/stl/deque/insert as a reference, I was inserting values into a deque at certain locations.

For example, if deque A was:

a, b, d, e, g

with an iterator pointing to d, i can:

A.insert(iter, c);    // insert val c before loc iter
//deque is now    a, b, c, d, e, g

and the iter still points to d. However, when iter points to g, the last element:

A.insert(iter, f);
//deque is now    a, b, c, d, e, f, g

but the iter now points to f!!

My current workaround is:

iter = A.insert(loc, val);  // point iterator to element that was inserted before loc
iter++;                     // point iter back to loc

I haven't tested this again or anything, it was annoying to have spent so much time tracking a bug down, just to discover insert()'s inconsistent behavior, in stl, of all places.

Why does insert() behave differently when at the end, compared to at any other location? Or is it that I did something wrong?

edit2: nvm

+7  A: 

Performing an insert invalidates all existing iterators, so you will get unpredictable behavior (possibly a crash) by reusing the old iterator.

Your workaround is the correct solution.

Edit: Regarding your second question, you are missing braces after if (*iter == 'g'). In the future though, please put new questions in a new post.

interjay
23.2.1.3 in the standard, for anyone wondering.
GMan
What other operations do this? Anything that changes the size() of the deque, like insert, erase, pop, push, resize? What about changing an element somewhere in the loop, like: *iter = 'z';
Kache4
It varies from container to container. For a `deque`, any insertions or deletions in the middle of the sequence will invalidate all existing iterators. Adding or removing from the ends will not. Also, if you're doing a lot of insertions in the middle of the sequence, you're probably better off using a `list` instead of a `deque`.
coppro
I have to use the deque for random access later. The insertions here are just for a one-time construction. My insertions are to purposely create duplicate entries at certain locations. However, you still have a good point, so I think I'll get around it by just building a brand new deque using the old deque's values for a worst case 2n.
Kache4