Hash Table Implementation in C++

  • 對於字符串,所用的hash函數爲:

    size_t _Hash_bytes(const void* ptr, size_t len, size_t seed) { node

    static const size_t mul = (((size_t) 0xc6a4a793UL) << 32UL) 函數

    + (size_t) 0x5bd1e995UL; oop

    const char* const buf = static_cast<const char*>(ptr); spa

       

    // Remove the bytes not divisible by the sizeof(size_t). This code

    // allows the main loop to process the data as 64-bit integers. 字符串

    const int len_aligned = len & ~0x7; hash

    const char* const end = buf + len_aligned; it

    size_t hash = seed ^ (len * mul); table

    for (const char* p = buf; p != end; p += 8) ast

    {

    const size_t data = shift_mix(unaligned_load(p) * mul) * mul;

    hash ^= data;

    hash *= mul;

    }

    if ((len & 0x7) != 0)

    {

    const size_t data = load_bytes(end, len & 0x7);

    hash ^= data;

    hash *= mul;

    }

    hash = shift_mix(hash) * mul;

    hash = shift_mix(hash);

    return hash;

    }

    其中ptr="VOA",len=3,seed=3339675911,返回的hash值爲5877402447214576471,模11後,獲得bucket位置爲6。

  • 默認的hash表桶數爲11。
  • unordered_set的實現,在insert調用棧中,會最終調用到:

    __node_type* __n = _M_find_node(__bkt, __k, __code),若是__k是首次插入,__n會等於nullptr,此時會轉入__n = __node_gen(std::forward<_Arg>(__v)),即生成新的_Hash_node。若是__n不爲nullptr,說明以前已有一樣元素存在。

  • 若是hash表元素是int,那麼會生成一個爲其特化的hashtable,其hash值不須要計算,而是直接用value % 11獲得其__bkt值,進而插入hash表。
相關文章
相關標籤/搜索