std::unordered_set 的元素的迭代顺序是否保证始终相同?
Is order of iteration over the elements of std::unordered_set guaranteed to be always the same?
如果多次迭代 std::unordered_set
的元素而不改变集合的内容(但可能从中读取,计算其大小等),是否保证元素将被访问每次都是同样的顺序?
在你提到的具体情况下,是的。因为该标准明确说明了何时进行重新散列(并因此重新排序)。
它只发生在插入过程中。
§ 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.
如果多次迭代 std::unordered_set
的元素而不改变集合的内容(但可能从中读取,计算其大小等),是否保证元素将被访问每次都是同样的顺序?
在你提到的具体情况下,是的。因为该标准明确说明了何时进行重新散列(并因此重新排序)。
它只发生在插入过程中。
§ 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.