• 一个极简易 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; } }); } };
  • 相关阅读:
    OZ Report 오즈 리포트 개발
    日期 英文 英语 韩文 韩语
    行合并
    R内存扩展 win7内存扩展
    计算日期函数
    C#颜色 Color.FromArgb ColorTranslator 16进制
    Phone
    浏览器 UserAgent
    context.Request.Files post 上传问题件
    The connection to adb is down, and a severe error has occured.
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4300363.html
Copyright © 2020-2023  润新知