-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayMap.h
110 lines (90 loc) · 1.76 KB
/
ArrayMap.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
#ifndef ARRAYMAP_H
#define ARRAYMAP_H
#include <vector>
#include <utility>
#include <algorithm>
template<typename K, typename V>
class ArrayMap
{
using Pair = std::pair<K, V>;
using PairVector = std::vector<Pair>;
PairVector data;
public:
using iterator = typename PairVector::iterator;
using const_iterator = typename PairVector::const_iterator;
using size_type = typename PairVector::size_type;
iterator begin()
{
return data.begin();
}
iterator end()
{
return data.end();
}
iterator cbegin()
{
return data.cbegin();
}
iterator cend()
{
return data.cend();
}
private:
iterator findSlot(const K & key)
{
return std::find_if(begin(), end(), [&key](const Pair & p)
{
return p.first >= key;
});
}
const_iterator findSlot(const K & key) const
{
return std::find_if(cbegin(), cend(), [&key](const Pair & p)
{
return p.first >= key;
});
}
public:
ArrayMap();
void reserve(size_type size)
{
data.reserve(size);
}
iterator find(const K & key)
{
return std::find_if(begin(), end(), [&key](const Pair & p)
{
return p.first == key;
});
}
const_iterator find(const K & key) const
{
return std::find_if(cbegin(), cend(), [&key](const Pair & p)
{
return p.first == key;
});
}
V & operator[](const K & key)
{
auto it = findSlot(key);
if (it == end() || it->first != key)
{
it = data.insert(it, Pair(key, V()));
}
return it->second;
}
V & operator[](K && key)
{
auto it = findSlot(key);
if (it == end() || it->first != key)
{
it = data.insert(it, Pair(key, V()));
}
return it->second;
}
};
template<typename K, typename V>
ArrayMap<K, V>::ArrayMap()
{
}
#endif // ARRAYMAP_H