哈希表C++实现(大概模型,有些细节没有考虑)

本文介绍了一种基于RS散列算法的哈希表实现方式,并通过C++代码示例展示了如何构造哈希表类、插入键值对及获取特定键对应的值。该哈希表采用链地址法解决冲突。
//HashTable.h
#include <string>
using std::string;

struct node
{
    int data;
    node* next;
    node()
    {
        data = INT_MAX;
        next = NULL;
    }
};

class HashTable
{
public:
    HashTable();
    HashTable(int);
    ~HashTable();
    int& operator[](const string);
    void SetValue(const string, int);
private:`
    int RSHash(const string);
    int size;
    node* ht;
};
//HashTable.cpp

#include <exception>
#include "HashTable.h"
using std::string;


HashTable::HashTable()
{
    ht = NULL;
    size = 0;
};

HashTable::HashTable(int ht_size)
{
    size = ht_size;
    ht = new node[ht_size]();
    //nothrow
};

HashTable::~HashTable()
{
    if (ht != NULL)
        delete ht;
};

int HashTable::RSHash(const string key)
{
    unsigned int b = 378551;
    unsigned int a = 63689;
    unsigned int hash = 0;

    for (int i = 0; i < key.size(); ++i)
    {
        hash = hash * a + key[i];
        a *= b;
    }

    return (hash & 0x7FFFFFFF) % size;
};

int& HashTable::operator[](const string key)
{
    node* res = ht[RSHash(key)].next;

    if (res != NULL)
        return res->data;
    else
        throw "Error: given key does not have a value!";
};

void HashTable::SetValue(const string key, int value)
{
    node* cur = &ht[RSHash(key)];

    while (cur->next != NULL)
        cur = cur->next;

    cur->next = new node();
    cur->next->data = value;
};


//main.cpp
#include <iostream>
#include <string>
#include <exception>
#include "HashTable.h"
using std::string;
using std::cout;

int main()
{
    HashTable* ht = new HashTable(100);
    ht->SetValue("Hit", 1);
    ht->SetValue("Make", 2);
    
    cout << (*ht)["Hit"] << std::endl;
    cout << (*ht)["Make"] << std::endl;    

    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值