-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhashtable.h
145 lines (126 loc) · 2.91 KB
/
hashtable.h
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#ifndef ALGORITHMS_HASHTABLE_H_
#define ALGORITHMS_HASHTABLE_H_
#include <functional>
#include <string>
#include <vector>
template <class O>
class hashobject {
public:
hashobject<O>();
hashobject<O>(size_t key, O value);
size_t m_key;
O m_value;
};
template <class O>
hashobject<O>::hashobject()
: m_key(-1) {
}
template <class O>
hashobject<O>::hashobject(size_t key, O value)
: m_key(key), m_value(value) {
}
template <class T>
class hashtable {
public:
hashtable<T>();
bool put(std::string key, T new_elem);
T get(std::string key);
bool remove(std::string );
private:
int reduce(size_t key);
const size_t MAX_SIZE = 1001;
std::vector<hashobject<T>> memory;
bool badalloc;
};
template <class T>
hashtable<T>::hashtable()
:badalloc(false) {
memory.resize(MAX_SIZE);
}
template <class T>
bool hashtable<T>::put(std::string key, T new_elem) {
std::hash<std::string> hash_fn;
size_t hash = hash_fn(key);
hashobject<T> obj(hash, new_elem);
unsigned int slot = reduce(hash);
unsigned int count = 0;
while (memory[slot].m_key != -1) {
// if key is the same, or deleted the overwrite
if (memory[slot].m_key == hash &&
memory[slot].m_key == 0) {
memory[slot].m_value = new_elem;
return true;
}
slot++;
if (slot >= MAX_SIZE) {
slot = 0;
}
if (count >= MAX_SIZE) {
return false;
}
count++;
}
memory[slot] = obj;
return true;
}
template <class T>
T hashtable<T>::get(std::string key) {
std::hash<std::string> hash_fn;
size_t hash = hash_fn(key);
unsigned int slot = reduce(hash);
if (memory[slot].m_key == -1) {
return false;
}
else {
int count = 0;
while (memory[slot].m_key != hash) {
slot++;
if (slot >= MAX_SIZE) {
slot = 0;
}
if (count >= MAX_SIZE) {
return false;
}
count++;
}
if (memory[slot].m_key > 0) {
return memory[slot].m_value;
}
else {
return false;
}
}
}
template <class T>
bool hashtable<T>::remove(std::string key) {
std::hash<std::string> hash_fn;
size_t hash = hash_fn(key);
unsigned int slot = reduce(hash);
if (memory[slot].m_key == -1) {
return false;
}
else {
int count = 0;
while (memory[slot].m_key != hash) {
slot++;
if (slot >= MAX_SIZE) {
slot = 0;
}
if (count >= MAX_SIZE) {
return false;
}
count++;
}
if (memory[slot].m_key > 0) {
memory[slot].m_key = 0;
}
else {
return false;
}
}
}
template <class T>
int hashtable<T>::reduce(size_t key) {
return key % MAX_SIZE;
}
#endif ALGORITHMS_HASHTABLE_H_