c++ - 循环 std::unordered_map,序列总是我插入元素的序列?

标签 c++ c++11 insert sequence unordered-map

我构建了一个 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/

相关文章:

c++ - 如何用一行代码初始化字符串类型的数组?

c++ - 正则表达式匹配字符串之间的数字

如果行不存在于没有唯一字段的表中,则 mysql 插入

mysql - 从 MySQL 中的大表中删除重复项的最快过程是什么

c++ - 如何从 C++ 文件中提取数据?

c++ - 为什么编译器会忽略模板类中的结构元素?

c++ - 程序员思维过程 : determining a maximum number of bytes to read when using ReadFile with the Windows API

c++ - 无法编译: error: expected primary-expression before '(' token

algorithm - 用于计算按时间和 key 划分的 Pearson 互相关矩阵的分布式算法

iphone - 如何将xml解析的内容插入sqlite3数据库