-
Notifications
You must be signed in to change notification settings - Fork 0
/
bounded_array.h
100 lines (90 loc) · 2.22 KB
/
bounded_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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#ifndef H_BOUNDED_ARRAY
#define H_BOUNDED_ARRAY
#include "debug.h"
/*
Stack allocated array containing a fixed amount of elements.
*/
template <typename T, size_t MAX_LENGTH>
class BoundedArray
{
public:
BoundedArray(){}
BoundedArray(T elements[MAX_LENGTH])
{
for(size_t i = 0; i < MAX_LENGTH; ++i)
{
this->elements[i] = elements[i];
}
this->length = MAX_LENGTH;
}
/**
Appends a single element to the end of the currently stored array
*/
void push(T element)
{
if(this->length >= MAX_LENGTH)
{
exception("Bounded array insertion would overflow");
}
this->elements[this->length] = element;
length++;
}
const T& operator[](const size_t index) const
{
if(index < length)
{
return elements[index];
}
else
{
exception("Bounded array access out of bounds");
return this->elements[0];
}
}
T& operator[](const size_t index)
{
if(index < length)
{
return elements[index];
}
else
{
exception("Bounded array access out of bounds");
return this->elements[0];
}
}
/*
* Returns the amount of elements in the array
*/
size_t size() const
{
return length;
}
/*
* "Removes" all elements in the array
*
* This is done by simply resetting length to 0
*/
void reset()
{
this->length = 0;
}
/**
* Searches for the specified needle in the array
*/
bool contains(T needle) const
{
for(size_t i = 0; i < length; ++i)
{
if((*this)[i] == needle)
{
return true;
}
}
return false;
}
private:
T elements[MAX_LENGTH];
size_t length = 0;
};
#endif