C++11:unordered_map/set 是否保证遍历顺序为插入顺序?
C++11: does unordered_map/set guarantees traversing order as insert order?
我写了一些这样的代码:
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
一样?
不,是unordered
,没有这样的保证。
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
都有效。
您可能还想检查这个问题
但是,在内部 unordered 容器的实现可能会使用 list
或其他 ordered 容器来存储元素并且只存储引用其桶中的子列表,这将使迭代顺序与插入顺序一致,直到插入足够多的元素导致列表重新排列。 VS实现就是这种情况。
我写了一些这样的代码:
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
一样?
不,是unordered
,没有这样的保证。
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
都有效。
您可能还想检查这个问题
但是,在内部 unordered 容器的实现可能会使用 list
或其他 ordered 容器来存储元素并且只存储引用其桶中的子列表,这将使迭代顺序与插入顺序一致,直到插入足够多的元素导致列表重新排列。 VS实现就是这种情况。