-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHashmap.cpp
More file actions
147 lines (123 loc) · 2.22 KB
/
Hashmap.cpp
File metadata and controls
147 lines (123 loc) · 2.22 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
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
146
147
// Hashmap
#include <iostream>
using namespace std;
class node{
public:
string key;
int value;
node* next;
node(string k,int v){
key = k;
value = v;
next = NULL;
}
};
class hashmap{
node** Bucket;
int ts;
int cs;
int hashFn(string key){
int ans = 0;
int mul_factor = 1;
for(int i=0;key[i]!='\0';i++){
ans += key[i]*mul_factor;
mul_factor *= 37;
ans%=ts;
mul_factor%=ts;
}
return ans%ts;
}
void rehash(){
node** oldBucket = Bucket;
int oldts = ts;
Bucket = new node*[2*ts];
ts = 2*ts;
cs = 0;
for(int i=0;i<ts;i++){
Bucket[i] = NULL;
}
for(int i=0;i<oldts;i++){
node* head = oldBucket[i];
while(head){
insert(head->key,head->value);
head=head->next;
}
delete oldBucket[i];
}
delete []oldBucket;
}
public:
hashmap(int s=7){
cs = 0;
ts = s;
Bucket = new node*[ts];
for(int i=0;i<ts;i++){
Bucket[i] = NULL;
}
}
void insert(string key,int value){
int i = hashFn(key);
node* n = new node(key,value);
n->next = Bucket[i];
Bucket[i] = n;
cs++;
float load_factor = cs/(ts*1.0);
if(load_factor>0.7){
rehash();
}
}
int* search(string key){
int i = hashFn(key);
node* head = Bucket[i];
while(head){
if(head->key == key){
return (&head->value);
}
head = head->next;
}
return NULL;
}
int& operator[](string key){
int* ans = search(key);
if(ans == NULL){
int garbage;
insert(key,garbage);
ans = search(key);
return *ans;
}
else{
return *ans;
}
}
void remove(string key)
{
int i=hashFn(key);
node* head=Bucket[i];
node* prev=NULL;
}
void Print(){
for(int i=0;i<ts;i++){
cout<<i<<"-->";
node* head = Bucket[i];
while(head){
cout<<"("<<head->key<<","<<head->value<<")";
head = head->next;
}
cout<<endl;
}
}
};
int main(){
hashmap h;
h.insert("Mango",100);
h.insert("Apple",150);
h.insert("Banana",50);
h.insert("Guava",30);
h.insert("Kiwi",60);
h.insert("PineApple",158);
//h["PineApple"] = 70; //insert
//h["PineApple"] = 170; //update
cout<<h["PineApple"]<<endl;
h.Print();
return 0;
}