This repository has been archived by the owner on Jan 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHash.cpp
95 lines (86 loc) · 2.54 KB
/
Hash.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include "Hash.h"
#include <iostream>
using std::string;
using std::list;
template <typename V>
Hash<V>::Hash(int size) {
height = size;
table = new list< Entry<V> >[size];
}
template <typename V>
Hash<V>::~Hash() {
delete[] table;
}
template <typename V>
void Hash<V>::insert(string key, V v) {
if(table[hash(key)].empty()) //empty spot
table[hash(key)].push_back(Entry<V>(key,v));
else{ //non-empty spot
typename list< Entry<V> >::iterator it;
bool inserted = false;
for(it = table[hash(key)].begin(); it != table[hash(key)].end() && inserted == false; it++) {
if(it->getKey() == key) {
it->setValue(v);
inserted = true;
}
}
if(inserted == false) { //non-empty and non-duplicate.
table[hash(key)].push_back(Entry<V>(key,v));
}
}
}
template <typename V>
void Hash<V>::remove(string key) {
if(!table[hash(key)].empty()){ // Non empty spot, no need to remove if empty
bool erased = false;
typename list< Entry<V> >::iterator it;
for(it = table[hash(key)].begin(); it != table[hash(key)].end() && erased == false; it++) {
if(it->getKey() == key) {
it = table[hash(key)].erase(it); // Erase it!
erased == true;
}
}
}
}
template <typename V>
V Hash<V>::get(string key) {
int hashed = hash(key);
if(!table[hashed].empty()) { // If the spot in the table is not empty...
typename list< Entry<V> >::iterator it; //
for(it = table[hashed].begin(); it != table[hashed].end(); it++) { // it = Entry obj in list
std::cout << hashed << std::endl;
if(it->getKey() == key) // And the key is the same...
return it->getValue(); // return the value.
}
} //else the key was not present in the table
return (V)0;
}
template <typename V>
int Hash<V>::hash(string key) {
int value = 0;
for(int i = 0; i < (int)key.length(); i++) {
value += key[i];
}
value = value%height;
return value;
}
template <typename V>
void Hash<V>::print() {
std::cout << "[ " ;
for(int i = 0; i < height; i++) {
std::cout << "{ " ;
if(!table[i].empty()){
typename list< Entry<V> >::iterator it;
for(it = table[i].begin(); it != table[i].end(); it++) {
std::cout << "(" << it->getKey() << ", " << it->getValue() << ") " ;
}
}
std::cout << " }";
if(i+1 != height)
std::cout << std::endl;
}
std::cout << " ]" << std::endl;
}
template class Hash<int>;
template class Hash<string>;
template class Hash<double>;