其他分享
首页 > 其他分享> > 关于C中STL容器的问题

关于C中STL容器的问题

作者:互联网

> std :: multimap和std :: unordered_multimap是否经常随机播放条目?我问,因为我的代码传递引用以区分具有相同哈希的条目,并且我想知道何时对它们运行引用重定向功能.
>如果我这样做会发生什么:

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];

>如果结果是unordered_multimap,结果会有所不同吗?
>返回传递引用以区分具有相同哈希的条目.有更安全的方法吗?
>如果删除其中一个条目,这些条目是否会移动(这是读取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.

同样,这并不需要重新调整实际存储的元素(unordered_map< Key,Value>中的Key和Value类型),因为无序映射具有组织为链表的存储桶,以及存储元素的迭代器(键值对) )同时具有元素指针和存储桶指针. reshshing shuffles buckets,它使迭代器无效(因为它们的bucket指针无效),但没有指针或对元素本身的引用.这在another Q&A中有详细说明

标签:multimap,unordered-map,c,c11,stl
来源: https://codeday.me/bug/20190725/1533436.html