std :: hash是否保证等于“相等”的哈希值?浮点数字? [英] Does std::hash guarantee equal hashes for "equal" floating point numbers?

查看:343
本文介绍了std :: hash是否保证等于“相等”的哈希值?浮点数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是浮点特化的 std :: hash (比如,对于 double s或 float s)关于 几乎平等 ?也就是说,如果两个值(例如(1./std::sqrt(5。)/ std :: sqrt(5。)) .2 )应该比较相等,但不会对 == 运算符这样做, std :: hash behave?



那么,我可以依靠 double 作为 std :: unordered_map 键可按预期工作?




散列浮点值,但要求提高;我在问C ++ 11的保证。

解决方案

std :: hash 对所有可以实例化
的类型都有同样的保证:如果两个对象相等,它们的哈希码将是
相等。否则,他们
不会有很大的可能性。因此,您可以依靠 double 作为
unordered_map 中的键来按预期工作:if two双打不是
等于(如 == 所定义),它们可能会有不同的
散列(即使它们不是,它们因为
unordered_map 也检查是否相等)。

显然,如果你的值是不准确的
计算的结果,它们不适用于 unordered_map
(也可能不适用于任何地图)的适当键。

Is the floating point specialisation of std::hash (say, for doubles or floats) reliable regarding almost-equality? That is, if two values (such as (1./std::sqrt(5.)/std::sqrt(5.)) and .2) should compare equal but will not do so with the == operator, how will std::hash behave?

So, can I rely on a double as an std::unordered_map key to work as expected?


I have seen "Hashing floating point values" but that asks about boost; I'm asking about the C++11 guarantees.

解决方案

std::hash has same guarantees for all types over which it can be instantiated: if two objects are equal, their hash codes will be equal. Otherwise, there's a very large probability that they won't. So you can rely on a double as a key in an unordered_map to work as expected: if two doubles are not equal (as defined by ==), they will probably have a different hash (and even if they don't, they're different keys, because unordered_map also checks for equality).

Obviously, if your values are the results of inexact calculations, they aren't appropriate keys for unordered_map (nor perhaps for any map).

这篇关于std :: hash是否保证等于“相等”的哈希值?浮点数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆