C++ deque: when iterators are invalidated

我是研究僧i 提交于 2019-11-28 05:27:09

push_back() and push_front() are defined in terms of insert(). Similarly, pop_back() and pop_front() are defined in terms of erase().

Here's what the C++03 standard says about iterator invalidation for insert() (23.2.1.3/1):

An insert in the middle of the deque invalidates all the iterators and references to elements of the deque. An insert at either end of the deque invalidates all the iterators to the deque, but has no effect on the validity of references to elements of the deque.

So push_front() and push_back() will invalidate iterators, but references to the elements themselves remain valid.

For erase() at either end (23.2.1.3/4):

An erase in the middle of the deque invalidates all the iterators and references to elements of the deque. An erase at either end of the deque invalidates only the iterators and the references to the erased elements.

So pop_front() and pop-back() only invalidate iterators/references to the element at the end in question.

And this is said says this about swap() for any standard container (23.1/10 "Container requirements"):

no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped.

C++11 adds the following clarifications regarding how the end() iterator on a deque behaves for these operations. Basically, an iterator to end() should be treated as invalid after a swap() or after erasing the last element in the deque:

An erase operation that erases the last element of a deque invalidates only the past-the-end iterator and all iterators and references to the erased elements.

Every iterator referring to an element in one container before the swap shall refer to the same element in the other container after the swap. It is unspecified whether an iterator with value a.end() before the swap will have value b.end() after the swap.

I think it would be a good idea to code as if these rules apply even if you're not yet using a C++11 compiler.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!