提问人:Raedwald 提问时间:8/6/2018 最后编辑:Shadow Wizard Is Sad And AngryRaedwald 更新时间:3/26/2019 访问量:5963
std::unordered_map 是否相等取决于插入顺序
Does std::unordered_map equality depend on insertion order
问:
如果使用同一组(不相等的)键值对创建两个容器,但以不同的顺序插入(因此容器包含相等的元素,但可能以不同的顺序),则根据相等运算符 (operator==
) 保证容器是相等的。我假设容器元素的哈希代码和相等运算符满足其实现所需的所有约束。std::unordered_map
答:
是的,在这种情况下,它们保证返回相等。具体措辞(来自N4659,§[unord.req]/12)是:
两个无序容器 和 比较相等 if 和 ,对于从 获取的每个等价键组,存在一个从 获取的等价键组,使得返回 。
a
b
a.size() == b.size()
[Ea1, Ea2)
a.equal_range(Ea1)
[Eb1, Eb2)
b.equal_range(Ea1)
is_permutation(Ea1, Ea2, Eb1, Eb2)
true
因此,只要一个键(和相关值)与另一个键相同(但可能以不同的排列顺序),它就会相等。
评论
std::is_permutation
operator==
operator==
std::is_permutation
find
equal_range
两个无序容器 和 比较相等 if 和 ,对于从 获取的每个等价键组,存在一个从 获取的等价键组,使得返回 。[...]
a
b
a.size() == b.size()
[Ea1, Ea2)
a.equal_range(Ea1)
[Eb1, Eb2)
b.equal_range(Ea1)
is_permutation(Ea1, Ea2, Eb1, Eb2)
true
因此,只要键相同且大小相同,无论键的顺序如何,容器的比较都是相等的。
以下是 cppreference.com 关于 std:unordered_map, operator==,!=(std::unordered_map) 的引述:
如果满足以下条件,则两个无序容器 lhs 和 rhs 的内容相等:
- lhs.size() == rhs.size()
- 从lhs.equal_range(lhs_eq1)获得的每一组等效元素[lhs_eq1,lhs_eq2)在从rhs.equal_range(rhs_eq1)获得的另一个容器[rhs_eq1,rhs_eq2)中都有一组相应的等效元素,该容器具有以下性质:
- std::d istance(lhs_eq1, lhs_eq2) == std::d istance(rhs_eq1, rhs_eq2).
- std::is_permutation(lhs_eq1, lhs_eq2, rhs_eq1) == true。
请注意:
如果 Key 或 T 不是 EqualityComparable,则行为未定义。
The behavior is also undefined if Hash and KeyEqual do (until C++20)KeyEqual does (since C++20) not have the same behavior on lhs and rhs or if operator== for Key is not a refinement of the partition into equivalent-key groups introduced by KeyEqual (that is, if two elements that compare equal using operator== fall into different partitions)
Finally, to consider is the complexity:
Proportional to N calls to operator== on value_type, calls to the predicate returned by key_eq, and calls to the hasher returned by hash_function, in the average case, proportional to N2 in the worst case where N is the size of the container.
Therefore, if both unordered maps have the same size, and each key in one of the containers is looked for in the other plus, if it happens to be found then their values are compared then they are the considered the same.
下一个:EJB 有什么用
评论