开发者

stl::deque's insert(loc, val) - inconsistent behavior at end of deque vs other locations?

Using http://www.cppreference.com/wiki/s开发者_Go百科tl/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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜