STL迭代器在收集更改后保证有效性吗? [英] Do STL iterators guarantee validity after collection was changed?

查看:152
本文介绍了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:


  1. 获取集合的迭代器。

  2. 修改集合(显然
    不是元素


  • 使用在步骤1获得的迭代器。根据STL标准,它是否有效?

    推荐答案

    取决于容器。例如如果它是一个向量,在修改容器后,所有迭代器可以无效。但是,如果它是列表,与修改的地方无关的迭代器将保持有效。

    Depends on the container. e.g. if it's a vector, after modifying the container all iterators can be invalidated. However, if it's a list, the iterators irrelevant to the modified place will remain valid.



    • 向量的迭代器在重新分配内存时失效。另外,插入或删除向量中间的元素使指向插入点或删除点之后的元素的所有迭代器无效。因此,如果使用 reserve()来预先分配与向量将使用的内存一样多的内存,并且如果所有插入和删除都是使用的,那么可以防止向量的迭代器无效在向量的结束。 [1]

    • A vector's iterators are invalidated when its memory is reallocated. Additionally, inserting or deleting an element in the middle of a vector invalidates all iterators that point to elements following the insertion or deletion point. It follows that you can prevent a vector's iterators from being invalidated if you use reserve() to preallocate as much memory as the vector will ever use, and if all insertions and deletions are at the vector's end. [1]

    deque 的迭代器无效的语义如下。 插入(包括 push_front push_back )会使所有迭代器请参阅 deque deque 中间的清除会使所有引用 deque deque (包括 pop_front >和 pop_back )只有当指向已擦除的元素时才会使迭代器无效。 [2]

    The semantics of iterator invalidation for deque is as follows. Insert (including push_front and push_back) invalidates all iterators that refer to a deque. Erase in the middle of a deque invalidates all iterators that refer to the deque. Erase at the beginning or end of a deque (including pop_front and pop_back) invalidates an iterator only if it points to the erased element. [2]

    List 具有重要的属性,插入和拼接不会使迭代器无效列表元素,甚至删除无效的指向被删除的元素的迭代器。 [3]

    Lists have the important property that insertion and splicing do not invalidate iterators to list elements, and that even removal invalidates only the iterators that point to the elements that are removed. [3]

    Map 有一个重要的属性,即在 map 中插入一个新元素不会使指向现有元素的迭代器无效。从映射中删除元素也不会使任何迭代器无效,当然,除了实际指向正在被擦除的元素的迭代器之外。 [4] (与相同 multiset multimap

    Map has the important property that inserting a new element into a map does not invalidate iterators that point to existing elements. Erasing an element from a map also does not invalidate any iterators, except, of course, for iterators that actually point to the element that is being erased. [4] (same for set, multiset and multimap)

    这篇关于STL迭代器在收集更改后保证有效性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆