STL迭代器是否保证集合更改后的有效性?
假设我有某种集合,并且我在它的开头获得了一个迭代器。现在假设我修改了该集合。无论集合或迭代器的类型如何,我仍然可以安全地使用迭代器吗?
为了避免混淆,这里是我讨论的操作顺序:
- 获取集合的迭代器。
- 修改集合(显然 不是其中的元素,而是集合本身)。
- 使用步骤1中获得的迭代器。根据STL标准它仍然有效吗?!
Let's say I have some kind of collection and I obtained an iterator for the beginning of it. Now let's say I modified the collection. Can I still use the iterator safely, regardless of the type of the collection or the iterator?
To avoid confusion, here is the order of operations I talk about:
- Get an iterator of the collection.
- Modify the collection (obviously
not an element in it, but the collection itself). - Use the iterator obtained at step 1. Is it stil valid according to STL standard?!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
取决于容器。例如,如果它是一个
向量
,则修改容器后,所有迭代器都会失效。但是,如果它是一个列表
,则与修改位置无关的迭代器将保持有效。Depends on the container. e.g. if it's a
vector
, after modifying the container all iterators can be invalidated. However, if it's alist
, the iterators irrelevant to the modified place will remain valid.这取决于相关的收藏。例如,修改 std::vector(例如,在某处添加元素)可能会使该向量中的所有迭代器无效。相比之下,对于
std::list
,当您向列表添加另一个元素时,迭代器仍然有效。在某些情况下,规则甚至更复杂(例如,如果内存可用,使用 std::deque,添加到开头或结尾会使现有迭代器有效,但添加到其他任何地方可能会使它们无效 - - 但我的记忆力很差,你应该在这之前检查一下)。That depends on the collection in question. Just for example, modifying a
std::vector
(e.g., adding an element somewhere) can invalidate all iterators into that vector. By contrast, with astd::list
, iterators remain valid when you add another element to the list. In some cases, the rules are even more complex (e.g., if memory serves, with astd::deque
, adding to the beginning or end leaves existing iterators valid, but adding anywhere else can invalidate them -- but my memory is sufficiently poor that you should check before depending on that).不,只有当被迭代的容器不变时,迭代器才有效。如果集合被修改,则应重新获取迭代器。
No, iterators are only good while the iterated container is unchanged. If a collection is modified, the iterator should be obtained anew.