-
Notifications
You must be signed in to change notification settings - Fork 0
/
DynArray.h
68 lines (60 loc) · 1.2 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
#pragma once
template<typename T>
class DynArray
{
public:
DynArray();
DynArray(int);
~DynArray();
bool Append(T item);
bool Truncate();
void Clear() { nData = nullptr; }
int Length() const { return nData; }
bool Empty() const { return nData == 0; }
const T& operator[](int i) const { return data[i]; }
T& operator[](int i) { return data[i]; }
public:
int nData;
int arraySize;
T *data;
};
template<typename T>
DynArray<T>::DynArray() : nData(0), arraySize(4), data(new T[arraySize])
{ }
template<typename T>
DynArray<T>::DynArray(int a) : nData(0), arraySize(a), data(new T[arraySize])
{ }
template<typename T>
DynArray<T>::~DynArray()
{
nData = 0;
delete[] data;
}
template<typename T>
bool DynArray<T>::Truncate()
{
if (nData != arraySize)
{
T *temp = data;
arraySize = nData;
if (!(data = new T[arraySize])) return false;
for (int i = 0; i < nData; i++) data[i] = temp[i];
delete[] temp;
}
return true;
}
template<typename T>
bool DynArray<T>::Append(T item)
{
if (nData == arraySize)
{
arraySize *= 2;
T *temp = data;
if (!(data = new T[arraySize])) return false;
for (int i = 0; i < nData; i++)
data[i] = temp[i];
delete[] temp;
}
data[nData++] = item;
return true;
}