-
Notifications
You must be signed in to change notification settings - Fork 0
/
absencearray.h
82 lines (67 loc) · 1.39 KB
/
absencearray.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
#pragma once
#include <initializer_list>
#include <optional>
#include <vector>
#include <map>
template <typename Type>
class AbsenceArray
{
public:
[[nodiscard]] Type* data()
{
return m_vector.data();
}
[[nodiscard]] size_t size() const
{
return m_vector.size();
}
[[nodiscard]] Type& operator[](const size_t index)
{
auto iterator = m_hash.find(m_vector[index]);
if (iterator != m_hash.end())
m_hash.erase(iterator);
return m_vector[index];
}
void clear()
{
m_vector.clear();
m_hash.clear();
}
size_t append(const Type& value)
{
const size_t index = m_vector.size();
m_vector.push_back(value);
return index;
}
size_t append(const std::initializer_list<Type>& list)
{
const size_t index = m_vector.size();
for (const Type& value : list)
m_vector.push_back(value);
return index;
}
[[nodiscard]] std::optional<size_t> find(const Type& value)
{
auto iterator = m_hash.find(value);
if (iterator != m_hash.end())
return iterator->second;
const size_t size = m_vector.size();
for (size_t i = 0; i < size; i++)
if (value == m_vector[i])
{
m_hash.insert({ value, i });
return i;
}
return std::nullopt;
}
size_t appendAbsent(const Type& value)
{
const auto index = find(value);
if (index.has_value())
return index.value();
return append(value);
}
private:
std::vector<Type> m_vector;
std::map<Type, size_t> m_hash;
};