根据
Igor的注释,C++标准没有指定算法,它
仅 要求哈希值仅依赖于对象,并且在程序运行期间保持不变:
http://eel.is/c++draft/hash.requirements。
20.5.3.4 哈希要求 [hash.requirements]
1 如果类型H满足以下条件,则类型H符合哈希要求:
- (1.1) 它是一个函数对象类型
- (1.2) 它满足可复制构造和可销毁的要求
- (1.3)
表29中显示的表达式有效并具有指示的语义。
2 给定Key是类型H的函数对象的参数类型,在表29中,h是类型(可能是const) H的值,u是类型Key的左值,k是可转换为(可能是const) Key的类型的值。
表29 - 哈希要求
- 表达式 返回类型 要求
- h(k) size_t 返回值仅取决于程序期间的参数k。[注意:因此,对于程序的给定执行,具有相同k值的所有h(k)表达式的评估都产生相同的结果。-end note] [注意:对于两个不同的值t1和t2,使得h(t1)和h(t2)比较相等的概率应该非常小,接近于1.0 / numeric_limits::max()。-end note]
- h(u) size_t 不得修改u。
Gcc的libstdc++实现使用std::hash的bitset:
https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/debug/bitset
#if __cplusplus >= 201103L
template<size_t _Nb>
struct hash<__debug::bitset<_Nb>>
: public __hash_base<size_t, __debug::bitset<_Nb>>
{
size_t
operator()(const __debug::bitset<_Nb>& __b) const noexcept
{ return std::hash<_GLIBCXX_STD_C::bitset<_Nb>>()(__b._M_base()); }
};
#endif
https://github.com/gcc-mirror/gcc/blob/1cb6c2eb3b8361d850be8e8270c597270a1a7967/libstdc%2B%2B-v3/include/std/bitset#L1561
template<size_t _Nb>
struct hash<_GLIBCXX_STD_C::bitset<_Nb>>
: public __hash_base<size_t, _GLIBCXX_STD_C::bitset<_Nb>>
{
size_t
operator()(const _GLIBCXX_STD_C::bitset<_Nb>& __b) const noexcept
{
const size_t __clength = (_Nb + __CHAR_BIT__ - 1) / __CHAR_BIT__;
return std::_Hash_impl::hash(__b._M_getdata(), __clength);
}
};
LLVM的libcxx使用自己的实现方式来处理bitset,将所有的单词进行异或操作:https://github.com/llvm-mirror/libcxx/blob/2c4b8af9aada61d83610330416eb8a39a8aa5494/include/bitset#L417
template <size_t _Size>
struct _LIBCPP_TEMPLATE_VIS hash<bitset<_Size> >
: public unary_function<bitset<_Size>, size_t>
{
_LIBCPP_INLINE_VISIBILITY
size_t operator()(const bitset<_Size>& __bs) const _NOEXCEPT
{return __bs.__hash_code();}
};
template <size_t _N_words, size_t _Size>
inline
size_t
__bitset<_N_words, _Size>::__hash_code() const _NOEXCEPT
{
size_t __h = 0;
for (size_type __i = 0; __i < _N_words; ++__i)
__h ^= __first_[__i];
return __h;
}
并且对于一个单词的位集,有一个更简单的变体:
inline
size_t
__bitset<1, _Size>::__hash_code() const _NOEXCEPT
{
return __first_;
}
std::bitfield
大小的值吗?也许是因为您想通过MPI发送它们。请在提问时提供完整的使用案例和背景信息,不要让我从您的个人资料中去猜测这一切。同时,请不要称那些花费自愿时间帮助您解决问题的人为“傲慢”。 - πάντα ῥεῖ