design-hashmap 1.0.0
Design HashMap
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3#define SIZE 100 // consider larger value, confront with overall performance for given use case
4
5using namespace std;
6
8{
9private:
10 // Hashtable. Array of lists of pairs (key, value)
11 vector<list<pair<int, int>>> table;
12
19 int hash(int key) { return key % SIZE; }
20
21public:
22 // Initialized my hashmap
24
28 void put(int key, int value)
29 {
30 int h = hash(key);
31 for (auto& p : table[h])
32 if (p.first == key)
33 {
34 p.second = value;
35 return;
36 }
37 table[h].emplace_back(key, value);
38 }
39
46 int get(int key)
47 {
48 int h = hash(key);
49 for (const auto& p : table[h])
50 if (p.first == key)
51 return p.second;
52 return -1;
53 }
54
60 void remove(int key)
61 {
62 int h = hash(key);
63 table[h].remove_if([key](const pair<int, int>& p) { return p.first == key; });
64 }
65};
66
67int main()
68{
69 MyHashMap* obj = new MyHashMap();
70 obj->put(1, 1);
71 obj->put(2, 2);
72 int value = obj->get(1);
73 cout << value << endl;
74 value = obj->get(3);
75 cout << value << endl;
76 obj->put(2, 1);
77 value = obj->get(2);
78 cout << value << endl;
79 obj->remove(2);
80 value = obj->get(2);
81 cout << value << endl;
82 delete obj;
83}
int hash(int key)
Returns index of table used as hashtable with given key.
Definition main.cpp:19
vector< list< pair< int, int > > > table
Definition main.cpp:11
MyHashMap()
Definition main.cpp:23
int get(int key)
Retrieves value of the key.
Definition main.cpp:46
void remove(int key)
Retrieves valid list and removes entry for key-value pair.
Definition main.cpp:60
void put(int key, int value)
Retrieves valid list and set/appends new value with given key.
Definition main.cpp:28
#define SIZE
Definition main.cpp:3
int main()
Definition main.cpp:67