-
Notifications
You must be signed in to change notification settings - Fork 5
/
Multi.h
95 lines (83 loc) · 2.42 KB
/
Multi.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
//
// Multi.h
//
// Created by Andrew Barker on 4/15/16.
//
//
#ifndef Multi_h
#define Multi_h
#include <vector>
// holds multiple, uniquely-IDed things (like a std::map, but underlying container is a vector)
template <class Thing>
class Multi
{
private:
// can't use POD's with inheritance
// class IDedThing : public Thing
// {
// public:
// template <class... Args>
// IDedThing(std::size_t idNumber, Args&&... args) : Thing(std::forward<Args>(args)...), idNum(idNumber) {}
// Thing thing;
// std::size_t idNum = 0;
// };
class IDedThing
{
public:
//IDedThing(std::size_t idNumber, Thing thing) : thing(thing), idNum(idNumber) {}
template <class... Args>
IDedThing(const std::size_t idNumber, Args&&... args) : thing(std::forward<Args>(args)...), idNum(idNumber) {}
Thing thing;
std::size_t idNum = 0;
};
std::vector<IDedThing> things;
public:
Thing* get(const std::size_t idNumber) noexcept
{
auto index = std::find_if(std::begin(things), std::end(things),
[&](const auto& thing){return thing.idNum == idNumber;})
- std::begin(things);
if (index < things.size())
return &things[index].thing;
else
return nullptr;
}
const Thing* get(const std::size_t idNumber) const noexcept
{
return get(idNumber);
}
std::vector<IDedThing>& getVector() noexcept
{
// std::vector<Thing> justThings;
// justThings.reserve(things.size());
// for (const auto& thing : things)
// justThings.emplace_back(thing);
// return justThings;
return things;
}
const std::vector<IDedThing>& getVector() const noexcept
{
return things;
}
template <class... Args>
void add(const std::size_t idNumber, Args&&... args)
{
remove(idNumber);
things.emplace_back(idNumber, std::forward<Args>(args)...);
}
void remove(const std::size_t idNumber)
{
things.erase(std::remove_if(std::begin(things), std::end(things),
[&](const auto& thing){return thing.idNum == idNumber;}),
std::end(things));
}
void clear() noexcept
{
things.clear();
}
std::size_t size()
{
return things.size();
}
};
#endif /* Multi_h */