-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashmap.cpp
More file actions
98 lines (86 loc) · 2.67 KB
/
hashmap.cpp
File metadata and controls
98 lines (86 loc) · 2.67 KB
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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// A simple hash map implementation using vector
class HashMap {
private:
static const int SIZE = 100; // Size of the hash table
vector<pair<string, int>> table[SIZE]; // Vector of pairs to handle collisions (chaining)
// Hash function: Calculates the index for a given key
int hashFunction(const string& key) {
int hash = 0;
for (char ch : key) {
hash = (hash + ch) % SIZE;
}
return hash;
}
public:
// Insert a key-value pair into the hash map
void insert(const string& key, int value) {
int index = hashFunction(key);
// Check if the key already exists and update the value if so
for (auto& pair : table[index]) {
if (pair.first == key) {
pair.second = value;
return;
}
}
// Otherwise, add a new key-value pair
table[index].push_back({key, value});
}
// Get the value associated with a key
int get(const string& key) {
int index = hashFunction(key);
for (const auto& pair : table[index]) {
if (pair.first == key) {
return pair.second;
}
}
throw runtime_error("Key not found");
}
// Check if a key exists in the hash map
bool contains(const string& key) {
int index = hashFunction(key);
for (const auto& pair : table[index]) {
if (pair.first == key) {
return true;
}
}
return false;
}
// Display the hash map content
void display() {
for (int i = 0; i < SIZE; i++) {
if (!table[i].empty()) {
cout << "Index " << i << ": ";
for (const auto& pair : table[i]) {
cout << "[" << pair.first << ": " << pair.second << "] ";
}
cout << endl;
}
}
}
};
int main() {
HashMap map;
// Insert some key-value pairs
map.insert("apple", 3);
map.insert("banana", 5);
map.insert("cherry", 7);
map.insert("date", 9);
// Display the hash map
cout << "HashMap contents:" << endl;
map.display();
// Get a value
try {
cout << "Value for 'apple': " << map.get("apple") << endl;
cout << "Value for 'banana': " << map.get("banana") << endl;
} catch (const exception& e) {
cout << e.what() << endl;
}
// Check if a key exists
cout << "Contains 'cherry': " << (map.contains("cherry") ? "Yes" : "No") << endl;
cout << "Contains 'grape': " << (map.contains("grape") ? "Yes" : "No") << endl;
return 0;
}