-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathArrayMap.h
More file actions
99 lines (84 loc) · 1.69 KB
/
Copy pathArrayMap.h
File metadata and controls
99 lines (84 loc) · 1.69 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
/*
* ArrayMap.h
*
*/
#ifndef ARRAYMAP_H_
#define ARRAYMAP_H_
#include <Arduino.h>
template<typename K, typename V>
class ArrayMap {
public:
ArrayMap(unsigned int capacity = 150, unsigned int capacityIncrease = 50) {
keys = NULL;
values = NULL;
this->capacity = 0;
this->capacityIncrease = capacityIncrease;
position = 0;
allocateCapacity(capacity);
}
~ArrayMap() {
}
void allocateCapacity(unsigned int capacity) {
K *newKeys = new K[capacity];
V *newValues = new V[capacity];
if (keys) {
for (int i = 0; i < position; i++) {
newKeys[i] = keys[i];
newValues[i] = values[i];
}
// delete keys;
// delete values;
}
keys = newKeys;
values = newValues;
this->capacity = capacity;
}
unsigned int size() const {
return position;
}
K keyAt(unsigned int idx) {
return keys[idx];
}
V valueAt(unsigned int idx) {
return values[idx];
}
unsigned int indexOf(K key) {
for (int i = 0; i < position; i++) {
if (key == keys[i]) {
return i;
}
}
return -1;
}
const V& operator[](const K key) const {
return operator[](key);
}
V& operator[](const K key) {
int index = indexOf(key);
if (index != -1) {
return values[index];
}
if (position == capacity) {
allocateCapacity(capacity + capacityIncrease);
}
keys[position] = key;
values[position] = dummyValue;
return values[position++];
}
void remove(K key) {
int index = indexOf(key);
if (index != -1) {
for (int i = index; i < capacity - 1; i++) {
keys[i] = keys[i + 1];
values[i] = values[i + 1];
}
position--;
}
}
protected:
int capacity, capacityIncrease, position;
K *keys;
V *values;
V dummyValue;
};
#endif /* ARRAYMAP_H_ */