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; } }); } };
  • 相关阅读:
    用js内置对象XMLHttpRequest 来用ajax
    HTTP 状态代码及其定义
    Delphi 字符类转换集《转》
    delphi 只允许运行一个实例的三种方法《转》
    时间加减函数(年、月、日)《转》
    删除数据库的表中某字段的值《转》
    Delphi 对话框《转》
    Delphi 给frxReport赋值《lcemeaning》
    点击链接弹出框提示《转》
    CentOS7上elasticsearch5.5启动报错
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4300363.html
Copyright © 2011-2022 走看看