Bitset<>用于unordered container时的默认hash函数

时间:2024-01-10 20:22:38

自从c++11起,bitset用于unordered container,将会提供默认的hash函数。

在gcc中,相关代码如下:

01495   // DR 1182.
01496 /// std::hash specialization for bitset.
01497 template<size_t _Nb>
01498 struct hash<_GLIBCXX_STD_D::bitset<_Nb>>
01499 : public std::unary_function<_GLIBCXX_STD_D::bitset<_Nb>, size_t>
01500 {
01501 size_t
01502 operator()(const _GLIBCXX_STD_D::bitset<_Nb>& __b) const
01503 {
01504 const size_t __clength = (_Nb + __CHAR_BIT__ - 1) / __CHAR_BIT__;
01505 return std::_Fnv_hash::hash(__b._M_getdata(), __clength);
01506 }
01507 };
01508
01509 template<>
01510 struct hash<_GLIBCXX_STD_D::bitset<0>>
01511 : public std::unary_function<_GLIBCXX_STD_D::bitset<0>, size_t>
01512 {
01513 size_t
01514 operator()(const _GLIBCXX_STD_D::bitset<0>&) const
01515 { return 0; }
01516 };

在vs2015中,相关代码如下:

// TEMPLATE STRUCT SPECIALIZATION hash
template<size_t _Bits>
struct hash<bitset<_Bits> >
{ // hash functor for bitset<_Bits>
typedef bitset<_Bits> argument_type;
typedef size_t result_type; size_t operator()(const argument_type& _Keyval) const
{ // hash _Keyval to size_t value by pseudorandomizing transform
return (_Keyval.hash());
}
};

我自己也写了一小段程序来试验bitset在unordered container中的用法:

#include <bitset>
#include <unordered_set>
#include <iostream>
#include "print.hpp"
using namespace std; int main()
{
bitset<3> bitset00(0);
bitset<3> bitset01(1);
bitset<3> bitset02(2);
bitset<3> bitset03(3);
bitset<3> bitset04(4);
bitset<3> bitset05(5);
bitset<3> bitset06(6);
bitset<3> bitset07(7); unordered_set<bitset<3>> coll = {bitset00, bitset01, bitset02, bitset03, bitset04, bitset05, bitset06, bitset07 };
PRINT_ELEMENTS(coll);
return 0;
}

注:其中print.hpp借用的是Nicolai M. Josuttis的The C++ Standard Library中的代码。

其输出如下:

000 001 010 011 100 101 110 111