c++ - 关于C++中STL容器的问题

标签 c++ c++11 stl unordered-map multimap

  1. std::multimap 和 std::unordered_multimap 多久洗一次次条目?我问是因为我的代码传递引用以区分具有相同散列的条目,我想知道何时对它们运行引用重定向函数。

  2. 如果我这样做会发生什么:

    std::multimap atable; //Type specification stuff left out
    //Code that pus in two entries with the same key, call that key foo
    int bar = atable[foo];
    
  3. 如果改为 unordered_multimap,结果是否不同?

  4. 回到传递引用以区分具有相同散列的条目。有更安全的方法吗?

  5. 如果我删除其中一个条目,这些条目是否会移动(这是阅读 std::vector 文档时的建议)?

最佳答案

不,在任何操作过程中都不会伤害任何元素。

this famous Q&A 中所述,对于关联容器,在插入/删除时没有迭代器失效(当然除了被删除的元素)。对于无序关联容器,在重新散列期间会出现迭代器失效,标准对此有说明(强调我的)

23.2.5 无序关联容器 [unord.req]

9 The elements of an unordered associative container are organized into buckets. Keys with the same hash code appear in the same bucket. The number of buckets is automatically increased as elements are added to an unordered associative container, so that the average number of elements per bucket is kept below a bound. Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements. For unordered_multiset and unordered_multimap, rehashing preserves the relative ordering of equivalent elements.

同样,这并不需要重新排列实际存储的元素(KeyValue 类型 unordered_map<Key, Value> ),因为无序映射具有组织为链表的桶,以及存储元素的迭代器(键值对)同时具有元素指针和桶指针。 rehashing 洗牌桶,这使迭代器无效(因为它们的桶指针无效)但不是指针或对元素本身的引用。这在 another Q&A 中有详细解释。

关于c++ - 关于C++中STL容器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18292433/

相关文章:

C++ 优先字典

c++ - 获得 c++11 - 兼容的编译器

c++ - 是否可以将 bitset<8> 的值复制到一串数组而不进行转换?

c++ - C++中的事件委托(delegate)

c++ - 比较 vector 和打印 bool

c++ - 在不解析 C++ 的情况下将 html 转换为纯文本?

c++ - 如何让 map 容器使用不同的构造函数创建一个新对象?

C++ - 已排序 std::vector 中元素的索引

c++ - std::map<int,bool> 插入结果错误?

c++ - 获取虚表指针c++