-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathunordered_map.cpp
135 lines (93 loc) · 1.81 KB
/
unordered_map.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
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
#include<iostream>
#include<vector>
#include<list>
using namespace std;
#define SIZE 100
template <class A,class B>
class unordered_map{
private:
vector< list <pair <A, B> > > map;
public:
unordered_map() {
map.resize(SIZE);
}
int calculate_hash(int key) {
key = ((key >> 16) ^ key) * 0x45d9f3b;
key = ((key >> 16) ^ key) * 0x45d9f3b;
key = (key >> 16) ^ key;
return key;
}
int calculate_hash(string key)
{
int seed = 131;
unsigned long hash = 0;
for(int i = 0; i < key.length(); i++)
{
hash = (hash * seed) + key[i];
}
return hash;
}
void insert(A key,B value)
{
int flag=0;
int index = calculate_hash(key)%SIZE;
for(auto it=map[index].begin();it!=map[index].end();it++)
{
if(it->first==key)
{
it->second=value;
flag=1;
break;
}
}
if(!flag)
map[index].push_back(make_pair(key,value));
}
void deleteEle(A key, B value)
{
int flag=0;
int index = calculate_hash(key)%SIZE;
for(auto it=map[index].begin();it!=map[index].end();it++)
{
if(it->first==key)
{
flag=1;
map[index].remove(make_pair(key,value));
break;
}
}
if(!flag)
cout<<"element doesnot exist";
}
void search(A key)
{
int flag=0;
int index = calculate_hash(key)%SIZE;
for(auto it=map[index].begin();it!=map[index].end();it++)
{
if(it->first==key)
{
cout<<"value is"<<it->second;
return ;
}
}
cout<<"element doesnot exist";
}
void display()
{
for(int i = 0; i < map.size(); i++) {
for(auto it=map[i].begin();it!=map[i].end();it++) {
cout<< it->first << " " << it->second;
}
}
}
};
int main()
{
unordered_map<string,int> mp;
mp.insert("hey",12);
mp.display();
mp.search("hey");
mp.deleteEle("bi",9);
return 0;
}