C++11的unordered_mapset在迭代时,是否严格遵循插入顺序的遍历规则?
- 内容介绍
- 文章标签
- 相关推荐
本文共计368个文字,预计阅读时间需要2分钟。
我编写了一些类似的代码,如下所示:cppunordered_map ui;ui.insert(make_pair(12, 4));ui.insert(make_pair(3, 2));ui.insert(make_pair(6, 1));ui.insert(make_pair(16, 9));// ...当使用for循环遍历此地图时,它将按照插入顺序显示正确的元素。
我写了一些像这样的代码:unordered_map<int, int> uii; uii.insert(make_pair(12,4)); uii.insert(make_pair(3,2)); uii.insert(make_pair(6,1)); uii.insert(make_pair(16,9)); ....
当我使用for循环访问此地图时,它按照我插入的正确顺序打印键.我测试了unordered_set,结果相同.
所以我的问题是,C标准是否保证访问顺序为插入顺序,就像Java的LinkedHashMap一样?
不,它是无序的,没有这样的保证.Elements in an unordered associative container are organized into
buckets, keys with the same hash will end up in the same bucket. The
number of buckets is increased when the size of the container
increases to keep the average number of elements in each bucket under
a certain value.Rehashing invalidates iterator and might cause the elements to be
re-arranged in different buckets but it doesn’t invalidate references
to the elements.
这对unordered_map和unordered_set都有效.
您可能还想查看此问题Keep the order of unordered_map as we insert a new key
但是,在内部,无序容器的实现可能使用列表或其他有序容器来存储元素并仅存储对其子列表中的子列表的引用,这将使迭代顺序与插入顺序一致,直到插入足够的元素以导致列表重新排列.这是VS实现的情况.
本文共计368个文字,预计阅读时间需要2分钟。
我编写了一些类似的代码,如下所示:cppunordered_map ui;ui.insert(make_pair(12, 4));ui.insert(make_pair(3, 2));ui.insert(make_pair(6, 1));ui.insert(make_pair(16, 9));// ...当使用for循环遍历此地图时,它将按照插入顺序显示正确的元素。
我写了一些像这样的代码:unordered_map<int, int> uii; uii.insert(make_pair(12,4)); uii.insert(make_pair(3,2)); uii.insert(make_pair(6,1)); uii.insert(make_pair(16,9)); ....
当我使用for循环访问此地图时,它按照我插入的正确顺序打印键.我测试了unordered_set,结果相同.
所以我的问题是,C标准是否保证访问顺序为插入顺序,就像Java的LinkedHashMap一样?
不,它是无序的,没有这样的保证.Elements in an unordered associative container are organized into
buckets, keys with the same hash will end up in the same bucket. The
number of buckets is increased when the size of the container
increases to keep the average number of elements in each bucket under
a certain value.Rehashing invalidates iterator and might cause the elements to be
re-arranged in different buckets but it doesn’t invalidate references
to the elements.
这对unordered_map和unordered_set都有效.
您可能还想查看此问题Keep the order of unordered_map as we insert a new key
但是,在内部,无序容器的实现可能使用列表或其他有序容器来存储元素并仅存储对其子列表中的子列表的引用,这将使迭代顺序与插入顺序一致,直到插入足够的元素以导致列表重新排列.这是VS实现的情况.

