hashtable的C++实现

hashtable的C++实现,使用两种常用的解决冲突的方式,使用时需要自己提供针对HashedObj的hash函数。

1、分离连接法(separate chaining)

复制代码
#include <vector>
#include <list>
using namespace std;

template <typename HashedObj>
class HashTable
{
  public:
    explicit HashTable(int size = 101);

    void makeEmpty()
    {
        for(int i = 0; i < theLists.size(); i++)
            theLists[i].clear();
    }

    bool contains(const HashedObj & x) const
    {
        const list<HashedObj> & whichList = theLists[myhash(x)];
        return find(whichList.begin(), whichList.end(), x) != whichList.end();
    }

    bool remove(const HashedObj & x)
    {
        list<HashedObj> & whichList = theLists[myhash(x)];
        typename list<HashedObj>::iterator itr = find(whichList.begin(), whichList.end(), x);
        if(itr == whichList.end())
            return false;
        whichList.erase(itr);
        --currentSize;
        return true;
    }

    bool insert(const HashedObj & x)
    {
        list<HashedObj> & whichList = theLists[myhash(x)];
        if(find(whichList.begin(), whichList.end(), x) != whichList.end())
            return false;
        whichList.push_back(x);
        if(++currentSize > theLists.size())
            rehash();
        return true;
    }

  private:
    vector<list<HashedObj> > theLists;   // The array of Lists
    int  currentSize;

    void rehash()
    {
        vector<list<HashedObj> > oldLists = theLists;

        // Create new double-sized, empty table
        theLists.resize(2 * theLists.size());
        for(int j = 0; j < theLists.size(); j++)
            theLists[j].clear();

        // Copy table over
        currentSize = 0;
        for(int i = 0; i < oldLists.size(); i++)
        {
            typename list<HashedObj>::iterator itr = oldLists[i].begin();
            while(itr != oldLists[i].end())
                insert(*itr++);
        }
    }

    int myhash(const HashedObj & x) const
    {
        int hashVal = hash(x);

        hashVal %= theLists.size();
        if(hashVal < 0)
            hashVal += theLists.size();

        return hashVal;
    }
};
复制代码

2、使用探测法(probing hash tables)

复制代码
template <typename HashedObj>
class HashTable
{
  public:
    explicit HashTable(int size = 101) : array(size)
    {
        makeEmpty();
    }

    void makeEmpty()
    {
        currentSize = 0;
        for(int i = 0; i < array.size(); i++)
            array[i].info = EMPTY;
    }

    bool contains(const HashedObj & x) const
    {
        return isActive(findPos(x));
    }

    bool insert(const HashedObj & x)
    {
        // Insert x as active
        int currentPos = findPos(x);
        if(isActive(currentPos))
            return false;

        array[currentPos] = HashEntry(x, ACTIVE);

        if(++currentSize > array.size()/2)
            rehash();

        return true;
    }

    bool remove(const HashedObj & x)
    {
        int currentPos = findPos(x);
        if(!isActive(currentPos))
            return false;
        array[currentPos].info = DELETED;
        return true;
    }

    enum EntryType { ACTIVE, EMPTY, DELETED };

  private:
    struct HashEntry
    {
         HashedObj element;
         EntryType info;
         HashEntry(const HashedObj & e = HashedObj(), EntryType i = EMPTY )
           : element(e), info(i) { }
    };

    vector<HashEntry> array;
    int currentSize;

    int findPos(const HashedObj & x) const
    {
        int offset = 1;
        int currentPos = myhash(x);

        while(array[currentPos].info != EMPTY && array[currentPos].element != x)
        {
            currentPos += offset;  // Compute ith probe
            offset += 2;
            if(currentPos >= array.size())
                currentPos -= array.size();
        }
        return currentPos;
    }

    bool isActive(int currentPos) const
    {
        return array[currentPos].info == ACTIVE;
    }

    void rehash()
    {
        vector<HashEntry> oldArray = array;

        // Create new double-sized, empty table
        array.resize(2*oldArray.size());
        for(int j = 0; j < array.size(); j++)
            array[j].info = EMPTY;

        // Copy table over
        currentSize = 0;
        for(int i = 0; i < oldArray.size(); i++)
            if(oldArray[i].info == ACTIVE)
                insert(oldArray[i].element);
    }

    int myhash(const HashedObj & x) const;
};
复制代码

 

作者:阿凡卢

出处:https://www.cnblogs.com/luxiaoxun/archive/2012/09/02/2667425.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   阿凡卢  阅读(10039)  评论(3编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示