-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray.h
78 lines (65 loc) · 1.26 KB
/
array.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
#pragma once
#include <vector>
#include <initializer_list>
#include <optional>
#include <map>
template <typename Type>
class Array
{
public:
[[nodiscard]] Type* data() noexcept
{
return vec.data();
}
[[nodiscard]] size_t size() const noexcept
{
return vec.size();
}
[[nodiscard]] Type& operator[](const size_t index)
{
hash.clear(); // TODO: maybe erase item instead
return vec[index];
}
void clear() noexcept
{
vec.clear();
hash.clear();
}
size_t append(const Type& value)
{
const size_t i = vec.size();
vec.push_back(value);
return i;
}
size_t append(const std::initializer_list<Type>& list)
{
const size_t i = vec.size();
for (const Type& value : list)
vec.push_back(value);
return i;
}
[[nodiscard]] std::optional<size_t> find(const Type& value)
{
auto iter = hash.find(value);
if (iter != hash.end())
return iter->second;
const size_t s = vec.size();
for (size_t i = 0; i < s; i++)
if (value == vec[i])
{
hash.insert({ value, i });
return i;
}
return std::nullopt;
}
size_t appendAbsent(const Type& value)
{
const std::optional<size_t> i = find(value);
if (i.has_value())
return i.value();
return append(value);
}
private:
std::vector<Type> vec;
std::map<Type, size_t> hash;
};