-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyMap.h
136 lines (123 loc) · 2.12 KB
/
MyMap.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
#ifndef MY_MAP
#define MY_MAP
// MyMap.h
template <typename KeyType, typename ValueType>
class MyMap
{
public:
MyMap()
{
m_size = 0;
root = nullptr;
}
~MyMap()
{
clear();
}
void clear()
{
deleteTree(root);
m_size = 0;
}
int size() const
{
return m_size;
}
void associate(const KeyType& key, const ValueType& value)
{
if (m_size == 0)
{
root = new Child(key, value);
m_size++;
return;
}
Child* it = root;
while (it != nullptr)
{
if (key == it->m_key)
{
it->m_value = value;
return;
}
if (key < (*it).m_key)
{
if (it->left == nullptr)
{
it->left = new Child(key, value);
m_size++;
return;
}
it = (*it).left;
}
else
{
if (it->right == nullptr)
{
it->right = new Child(key, value);
m_size++;
return;
}
it = (*it).right;
}
}
}
// for a map that can't be modified, return a pointer to const ValueType
const ValueType* find(const KeyType& key) const
{
Child* it = root;
while (it != nullptr)
{
if (it->m_key == key)
{
ValueType* vp = &(it->m_value);
return vp;
}
else if (key<it->m_key)
{
it = it->left;
}
else if (key>it->m_key)
{
it = it->right;
}
}
return nullptr;
}
// for a modifiable map, return a pointer to modifiable ValueType
ValueType* find(const KeyType& key)
{
return const_cast<ValueType*>(const_cast<const MyMap*>(this)->find(key));
}
// C++11 syntax for preventing copying and assignment
MyMap(const MyMap&) = delete;
MyMap& operator=(const MyMap&) = delete;
private:
int m_size;
class Child
{
public:
Child()
{}
Child(KeyType key,ValueType value)
{
m_key = key;
m_value = value;
left = nullptr;
right = nullptr;
}
Child* left;
Child* right;
KeyType m_key;
ValueType m_value;
};
Child* root;
void deleteTree(Child* cur)
{
if (cur == NULL)
return;
deleteTree(cur->left);
deleteTree(cur->right);
delete cur;
}
};
#endif