-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleMap.h
171 lines (146 loc) · 2.13 KB
/
SimpleMap.h
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#pragma once
#include <iostream>
#include <string>
using namespace std;
class SimpleMap
{
int size = 0;
int capacity = 16;
public:
class Entry
{
string key = "";
int value = 0;
public:
Entry(string key, int value)
{
this->key = key;
this->value = value;
}
string GetKey() const
{
return key;
}
int GetValue() const
{
return value;
}
void SetValue(int value)
{
this->value = value;
}
};
private:
Entry** values = new Entry* [capacity];
public:
SimpleMap()
{
for (int i = 0; i < capacity; i++)
{
values[i] = nullptr;
}
}
int Get(const string& key)
{
for (int i = 0; i < size; i++)
{
if (values[i] != nullptr)
{
if (values[i]->GetKey() == key)
{
return values[i]->GetValue();
}
}
}
return -1;
}
int operator[](const string& key)
{
return Get(key);
}
void Put(const string& key, int value)
{
bool insert = true;
for (int i = 0; i < size; i++)
{
if (values[i]->GetKey() == key)
{
values[i]->SetValue(value);
insert = false;
}
}
if (insert)
{
EnsureCapacity();
values[size++] = new Entry(key, value);
}
}
private:
void EnsureCapacity()
{
if (size == capacity)
{
capacity *= 2;
Entry** temp = new Entry* [capacity];
for (int i = 0; i < capacity; i++)
{
if (i < size) temp[i] = values[i];
else temp[i] = nullptr;
}
delete[] values;
values = temp;
}
}
public:
int GetSize() const
{
return size;
}
void Remove(const string& key)
{
for (int i = 0; i < size; i++)
{
if (values[i]->GetKey() == key)
{
values[i] = nullptr;
size--;
CondenseArray(i);
}
}
}
private:
void CondenseArray(int start)
{
for (int i = start; i < size; i++)
{
values[i] = values[i + 1];
}
}
};
/*
// code for main:
SimpleMap map;
map.Put("Valera", 11);
map.Put("Olga", 12);
map.Put("Dima", 9);
if (map.Get("Andrew") == 11)
{
cout << "yes 1\n";
}
for (int i = 0; i < 10; i++)
{
map.Put(to_string(i), i);
}
if (map.GetSize() == 13)
{
cout << "yes 2\n";
}
if (map.Get("5") == 5)
{
cout << "yes 3\n";
}
if (map["7"] == 7)
{
cout << "yes 4\n";
}
*/