我构建了一个 std::unordered_map 并使用 for 循环访问它。 我发现迭代结果的顺序显示元素是按照我创建这些元素的顺序放置的,无论我如何插入它们。
这部分C++标准是unordered_map,访问时,迭代顺序是插入顺序?或者这是实现偏好?
我问的这个问题是,我想知道这个特性是否可以在我的 C++ 代码中依赖?
最佳答案
没有。该标准不保证无序关联容器 †(无序映射、集合及其多值版本)中元素的顺序,您不能依赖代码中的任何特定顺序。
† 特殊情况除外[unord.req]/6 (标准草案,强调我的):
An unordered associative container supports unique keys if it may contain at most one element for each key. Otherwise, it supports equivalent keys. unordered_set and unordered_map support unique keys. unordered_multiset and unordered_multimap support equivalent keys. In containers that support equivalent keys, elements with equivalent keys are adjacent to each other in the iteration order of the container. Thus, although the absolute order of elements in an unordered container is not specified, its elements are grouped into equivalent-key groups such that all elements of each group have equivalent keys. Mutating operations on unordered containers shall preserve the relative order of elements within each equivalent-key group unless otherwise specified.
关于c++ - 循环 std::unordered_map,序列总是我插入元素的序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41404733/