include iostream include vector using namespace std template typename

 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
#include <iostream>
#include <vector>
using namespace::std;
template <typename K, typename V>
class HashTable {
private:
vector<K> keys;
vector<V> values;
public:
HashTable() {}
void add(const K& key,const V& value) {
keys.push_back(key);
values.push_back(value);
}
V search(const K& key) {
for (int i = 0; i < keys.size(); i++) {
if (keys[i] == key)
return values[i];
}
return NULL;
}
void remove(const K& key) {
for (int i = 0; i < keys.size(); i++) {
if (keys[i] == key) {
keys.erase(keys.begin() + i);
values.erase(values.begin() + i);
break;
}
}
}
V operator[](const K& key) {
return search(key);
}
~HashTable() {}
};
int main() {
HashTable<string, int> hash;
hash.add("key1", 1);
hash.add("key2", 2);
hash.add("key3", 3);
cout << hash.search("key2") << endl;
hash.remove("key2");
cout << hash.search("key2") << endl;
return 0;
}