-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStableVector.h
102 lines (100 loc) · 2.53 KB
/
StableVector.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
#pragma once
#include <forward_list>
#include <iterator>
namespace labbish {
template <typename T>
class StableVector :public std::forward_list<T> {
public:
inline StableVector() = default;
inline StableVector(const std::initializer_list<T>& init) :std::forward_list<T>() {
auto it = this->before_begin();
for (const T& value : init) {
it = this->insert_after(it, value);
}
}
inline size_t size() const {
return std::distance(this->begin(), this->end());
}
inline T& operator[](size_t index) {
auto it = this->begin();
size_t currentIndex = 0;
while (it != this->end()) {
if (currentIndex == index) {
return *it;
}
++it;
++currentIndex;
}
throw std::out_of_range(std::format("StableVector index out of range: {}", index));
}
inline const T& operator[](size_t index) const {
auto it = this->begin();
size_t currentIndex = 0;
while (it != this->end()) {
if (currentIndex == index) {
return *it;
}
++it;
++currentIndex;
}
throw std::out_of_range(std::format("StableVector index out of range: {}", index));
}
inline void push_back(const T& value) {
if (this->empty()) {
this->push_front(value);
return;
}
auto it = this->begin();
while (std::next(it) != this->end()) {
++it;
}
this->insert_after(it, value);
}
inline void pop_back() {
if (this->empty()) {
throw std::out_of_range("StableVector is empty");
}
if (this->size() == 1) {
this->pop_front();
return;
}
auto it = this->begin();
while (std::next(it) != this->end() && std::next(std::next(it)) != this->end()) {
++it;
}
this->erase_after(it);
}
inline void erase(size_t index) {
if (index >= this->size()) {
throw std::out_of_range(std::format("StableVector index out of range: {}", index));
}
if (index == 0) {
this->pop_front();
return;
}
auto it = this->begin();
size_t currentIndex = 0;
while (currentIndex < index - 1) {
++it;
++currentIndex;
}
this->erase_after(it);
}
inline void insert(size_t index, const T& value) {
if (index > this->size()) {
throw std::out_of_range(std::format("StableVector index out of range: {}", index));
}
if (index == 0) {
this->push_front(value);
return;
}
auto it = this->begin();
size_t currentIndex = 0;
while (currentIndex < index - 1) {
++it;
++currentIndex;
}
this->insert_after(it, value);
}
};
}