forked from freme/raybeam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynarray.h
78 lines (59 loc) · 1.71 KB
/
dynarray.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
// dynarray.h
#ifndef _DYNARRAY_H_
#define _DYNARRAY_H_ 1
// doubles array size if full, use truncate() to manually free empty space
// add items via append()
template <class T> class DynArray {
public:
DynArray();
DynArray(int);
~DynArray();
bool append(T item); //adds to the end of array
bool truncate(); //free empty cells
void clear() {nData = 0; }
int length() const { return nData; }
int size() const { return arraySize; }
bool empty() const { return nData == 0; }
const T& operator[](int i) const { return data[i]; }
T& operator[](int i) { return data[i]; }
T* data;
int nData;
int arraySize;
};
template <class T> DynArray<T>::DynArray() {
nData = 0;
arraySize = 4;
data = new T[arraySize];
}
template <class T> DynArray<T>::DynArray(int a) {
nData = 0;
arraySize = a;
data = new T[arraySize];
}
template <class T> DynArray<T>::~DynArray() {
nData = 0;
delete [] data;
}
template <class T> bool DynArray<T>::truncate() {
if (nData != arraySize) {
T* tmp = data;
arraySize = nData;
if (!(data = new T[arraySize])) return false;
for (int i = 0; i < nData; i++) data[i] = tmp[i]; //deep copy
delete [] tmp;
}
return true;
}
template <class T> bool DynArray<T>::append(T item) {
// double array if no more space available
if (nData == arraySize) {
arraySize *= 2;
T* tmp = data;
if (!(data = new T[arraySize])) return false;
for (int i = 0; i < nData; i++) data[i] = tmp[i];
delete [] tmp;
}
data[nData++] = item;
return true;
}
#endif // _DYN_ARRAY_H_