문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top