只做了增删查,基本的数据类型和字符串
template<class T>
class HashMap {
template<class T>//基本数据类型
struct item
{
T _value;
item<T>* _next;//用链表,无需扩容
explicit item(T value = 0) :_next(nullptr), _value(value){}
};
template<>
struct item<const char*>//其实不止字符串要特化,还有很多可能的自定义类型
{
char* _cstr;
item<const char*>* _next;
explicit item(const char* c) :_next(nullptr){
if (c != nullptr) {
_cstr = new char[strlen(c) + 1];
strcpy_s(_cstr, strlen(c) + 1, c);
}
else _cstr = nullptr;
}
~item() {
if (_cstr)delete[] _cstr;
}
};
typedef item<T> Node;
static const int _init_size = 10;//本例哈希函数的值为0-9 //必须static
Node* _hashtable[_init_size];
int _capacity;
int _size;
public:
HashMap(): _size(0), _capacity(_init_size){
for (int i = 0; i < _capacity; i++) {
_hashtable[i] = new Node;
}
}
~HashMap() {
Node* node,*temp;
for (int i = 0; i < _capacity; i++) {
node = _hashtable[i];
while (node) {
temp = node;
node = node->_next;
delete temp;
}
}
}
template<class T>
Node* find(T key) {
int hash = hashfunc(key);
Node* node = _hashtable[hash]->_next;
for (; node; node = node->_next) {
if (node->_value == key)return node;
}
return nullptr;
}
void insert(T key) {
Node* node = new Node(key);
int hash = hashfunc(key);
//cout << "insert=" << key << endl;
//cout << hash << endl;
Node* temp = _hashtable[hash]->_next;
_hashtable[hash]->_next = node;
node->_next = temp;
_size++;
}
template<class T>
bool remove(T key) {
int hash = hashfunc(key);
Node* node = _hashtable[hash],*temp;
for (; node->_next; node = node->_next) {
if (node->_next->_value == key) {
temp = node->_next;
node->_next = node->_next->_next;
delete temp;
_size--;
return true;
}
}
return false;
}
template<>
bool remove(const char* c) {
int hash = hashfunc(c);
Node* node = _hashtable[hash], * temp;
for (; node->_next; node = node->_next) {
if (strcmp(node->_next->_value, c) == 0) {
temp = node->_next;
node->_next = temp->_next;
delete temp;
return true;
}
}
return false;
}
private:
template<class T>//基本数据类型的哈希函数
int hashfunc(T value) {
return (value % _capacity);
}
template<>
int hashfunc(char *cstr) {
//if (c == nullptr)return 0;
const char *c = cstr;
int hash = 0;
while (*c) {
hash = *c + hash * 33;
c++;
}
return (hash % _capacity);
}
};
void test02() {
char* cc[10];
for (int i = 0; i < sizeof(cc) / sizeof(*cc); i++) {
cc[i] = new char[2]{ 0 };
(cc[i])[0] = 97 + i;
}
for (int i = 0; i < sizeof(cc) / sizeof(*cc); i++) {
cout << cc[i] << endl;
}
HashMap<char*> hm;
//for (int i : a)hm.insert(i);
for (int i = 0; i < sizeof(cc) / sizeof(*cc); i++) {
hm.insert(cc[i]);
}
for (int i = 0; i < sizeof(cc) / sizeof(*cc); i++) {
cout << hm.find(cc[i])->_value << endl;
}
for (int i = 0; i < sizeof(cc) / sizeof(*cc); i++) delete[] cc[i];
}