C++容器的迭代器失效规则是什么?
优选地以摘要列表格式.
(注意:这是Stack Overflow的C++常见问题解答的一个条目.如果你想批评在这种形式下提供常见问题解答的想法,那么发布所有这些的元数据的发布将是这样做的地方.这个问题在C++聊天室中受到监控,其中FAQ的想法一开始就出现了,所以你的答案很可能被那些提出想法的人阅读.)
我试图利用这样一个事实,即插入和删除之后列表的迭代器仍然有效(除了刚刚删除的迭代器之外).这也是如此std::list<T>::end();
假设我尝试以下方法:
typedef std::list<int> list_int;
list_int myList;
list_int::iterator iter = myList.end();
myList.push_back(1);
myList.push_back(2);
myList.push_back(3);
if(iter == myList.end()) {
/* do things here */
} else {
/* do different things here */
/* I don't expect this branch to ever execute */
}
Run Code Online (Sandbox Code Playgroud)
This is important because elsewhere I might store a collection of iterators into this list, and I would test for validity by comparing against myList.end(). It's important that invalid iterators remain so even after insertions …