zoukankan      html  css  js  c++  java
  • 一个极简易 int 类型哈希表的实现

    看了算法导论的影印版的哈希表时,开始还不太明白, 想了下后觉得似乎哈希表就是数组和链表的组合, 于是根据这个思路实现了一个最简易的哈希表。

    这个其实我还是不太满意, 可能在以后会更新, 因为我觉得不满足 DRY 原则。

    class HashTable
    {
    private:
        const size_t             initSize = 13;
        const int32_t            hashNum  = 13;
    
        vector<list<int32_t>>    hashTable;
    
        int32_t Hash (const int32_t& key) const
        {
            return (key % hashNum);
        }
    
        list<int32_t>::const_iterator
            GetTargetIter (const int32_t& value) const
        {
            auto key = Hash (value);
            return find (hashTable[key].cbegin (),
                         hashTable[key].cend (),
                         value);
        }
    
    public:
        explicit HashTable ()
        {
            hashTable.resize (initSize);
        }
    
        decltype(hashTable) GetHashTable () const
        {
            return hashTable;
        }
    
        HashTable& operator=(const HashTable& otherTable)
        {
            hashTable = otherTable.GetHashTable ();
            return *this;
        }
    
        void Insert (const int32_t& value)
        {
            if (GetTargetIter (value) ==
                hashTable[Hash (value)].cend ()) {
                hashTable[Hash (value)].push_back (value);
            }
            else {
                cerr << "Insert failed: The value already exists. ";
            }
        }
    void Delete (const int32_t& value) { auto targetIter = GetTargetIter (value); auto key = Hash (value); if (targetIter == hashTable[key].cend ()) { cout << "Cannot find " << value << " ! "; } else { hashTable[key].erase (targetIter); cout << "The " << value << " has been deleted! "; } } void Search (const int32_t& value) const { if (GetTargetIter (value) == hashTable[Hash (value)].cend ()) { cout << "Cannot find "<< value << " ! "; } else { cout << value << " is exist. "; } } void Show () const { cout << "The values in the hash table are: "; for_each (hashTable.cbegin (), hashTable.cend (), [] (const list<int32_t>& l) { if (!l.empty ()) { for (const auto& val : l) { cout << val << " "; } cout << endl; } }); } };
  • 相关阅读:
    php
    nginx
    docker
    pyenv 配置python虚拟环境
    [运维笔记] Nginx编译安装
    [运维笔记] Mysql单库备份脚本
    BurpSuite Intruder 4种攻击模式
    java判断一个单向链表是否有环路
    二分查找(递归和非递归)
    反转链表算法题
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4300363.html
Copyright © 2011-2022 走看看