hash table(开放寻址法-线性探查实现的哈希表)
//
// Created by 许加权 on 2021/7/17.
//#ifndef C11LEARN_HASHLINER_H
#define C11LEARN_HASHLINER_H
#include "KeyNode.h"
template<typename T>
class HashLiner
{
public:HashLiner();HashLiner(const HashLiner<T> & hashLiner);~HashLiner();const HashLiner<T>& operator=(const HashLiner<T> & hashLiner);T & operator[](int key);
protected:long long capacity;KeyNode<T>** array;long long w;long long p;long long s;long long two_32;
protected:virtual int auxiliary_hashing(int key);virtual int hashing(int key,int index);void insert(KeyNode<T>* node);KeyNode<T>*search(int key);void clear();void copy(const HashLiner<T> & hashLiner);
};template<typename T>
HashLiner<T>::HashLiner(){s = 2654435769;w = 32;p = 14;two_32 = 1;two_32 = two_32<<32;capacity = 1<<p;array = new KeyNode<T>*[capacity];
}
template<typename T>
HashLiner<T>::HashLiner(const HashLiner<T> & hashLiner){s = 2654435769;w = 32;p = 14;two_32 = 1;two_32 = two_32<<32;capacity = 1<<p;array = new KeyNode<T>*[capacity];copy(hashLiner);
}
template<typename T>
HashLiner<T>::~HashLiner(){clear();if(array!= nullptr){delete [] array;array = nullptr;}
}
template<typename T>
void HashLiner<T>::copy(const HashLiner<T> & hashLiner){for (int i = 0; i < capacity; ++i) {if(hashLiner.array[i]!= nullptr){array[i] = new KeyNode<T>(hashLiner.array[i]->key,hashLiner.array[i]->value);}}
}
template<typename T>
const HashLiner<T>& HashLiner<T>::operator=(const HashLiner<T> & hashLiner){if(this == &hashLiner) return *this;clear();copy(hashLiner);return *this;
}
template<typename T>
T & HashLiner<T>::operator[](int key){KeyNode<T>* node = search(key);if(node == nullptr){node = new KeyNode<T>();node->key = key;insert(node);}return node->value;
}
template<typename T>
int HashLiner<T>::auxiliary_hashing(int key){return ((key*s)%two_32)>>(w-p);
}
template<typename T>
int HashLiner<T>::hashing(int key,int index){return (auxiliary_hashing(key)+index) % capacity;
}
template<typename T>
void HashLiner<T>::insert(KeyNode<T>* node){int i = -1;int j;while (++i<capacity){j = hashing(node->key,i);if(array[j] == nullptr) {array[j] = node;return;}}throw "hash table overflow";
}
template<typename T>
KeyNode<T>* HashLiner<T>::search(int key){int i = -1;int j;while (++i<capacity){j = hashing(key,i);if(array[j] == nullptr)return nullptr;if(array[j]->key == key)return array[j];}return nullptr;
}
template<typename T>
void HashLiner<T>::clear(){for (int i = 0; i < capacity; ++i) {if(array[i]!= nullptr){delete array[i];array[i] = nullptr;}}
}
#endif //C11LEARN_HASHLINER_H
测试代码
HashLiner<string> hashLiner;hashLiner[2] = "hello";hashLiner[123456] = "world";cout << hashLiner[2] << endl;cout << hashLiner[123456] << endl;HashLiner<string> hashLiner1 = hashLiner;cout << hashLiner1[2] << endl;cout << hashLiner1[123456] << endl;HashLiner<string> hashLiner2;hashLiner2 = hashLiner;cout << hashLiner2[2] << endl;cout << hashLiner2[123456] << endl;
辅助类
KeyNode地址
辅助auxiliary_hashing函数是利用乘法散列法实现的