-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTable.cpp
57 lines (46 loc) · 1.21 KB
/
HashTable.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
#include "HashTable.h"
HashTable::HashTable(int s) {
size = s;
hashTable = new list<TokenObject>[size];
}
void HashTable::decode_put(TokenObject& obj) {
int bucket = computeHash(obj);
if (hashTable[bucket].empty()) {
hashTable[bucket].push_back(obj);
}
else {
cout << "Error: hashTable[bucket] not empty" << endl;
exit(1);
}
}
void HashTable::encode_put(TokenObject& obj) {
int bucket = computeHash(obj.getWord());
hashTable[bucket].push_back(obj);
}
TokenObject HashTable::decode_access(int code) {
return *hashTable[code % size].begin();
}
TokenObject HashTable::encode_access(string word) {
int bucket = computeHash(word);
list<TokenObject>::iterator it;
for (it = hashTable[bucket].begin(); it != hashTable[bucket].end(); it++) {
if (it->getWord() == word) {
return *it;
}
}
cout << "Error: encode_access couldn't return TokenObject for string: \"" << word << "\"" << endl;
exit(1);
}
int HashTable::getSize() {
return size;
}
int HashTable::computeHash(TokenObject& obj) {
return obj.getCode() % size;
}
int HashTable::computeHash(string& word) {
int hashValue = 0;
for (unsigned int i = 0; i < word.size(); ++i) {
hashValue += int(word.at(i)) * (i + 1);
}
return (hashValue % size);
}