-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenericArray.h
114 lines (113 loc) · 1.95 KB
/
GenericArray.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
103
104
105
106
107
108
109
110
111
112
113
114
#pragma once
#include <iostream>
#include <string>
using namespace std;
template <class T>
class GenericArray
{
T* data;
int capacity;
bool isValidIndex(int index) const
{
return index >= 0 && index < capacity;
}
public:
GenericArray()
{
capacity = 0;
data = nullptr;
}
GenericArray(int size) : GenericArray()
{
if (size <= 0)
return;
capacity = size;
data = new T[capacity];
}
GenericArray(initializer_list<T> l) : GenericArray()
{
capacity = l.size();
if (capacity <= 0)
{
data = nullptr;
return;
}
data = new T[capacity];
int i = 0;
for (auto val : l)
data[i++] = val;
}
~GenericArray()
{
if (data)
{
delete[]data;
data = nullptr;
}
capacity = 0;
}
void resize(int newCapacity)
{
if (newCapacity <= 0)
{
this->~GenericArray();
return;
}
T* ptr = new T[newCapacity];
if (capacity > 0)
{
int size = newCapacity < capacity ? newCapacity : capacity;
for (int i = 0; i < size; i++)
ptr[i] = data[i];
}
this->~GenericArray();
capacity = newCapacity;
data = ptr;
}
T& operator[](int i)
{
if (isValidIndex(i))
return data[i];
exit(0);
}
T& operator[](int i) const
{
if (isValidIndex(i))
return data[i];
exit(0);
}
GenericArray<T>& operator=(const GenericArray<T> & ref)
{
if (this == &ref)
return *this;
this->~GenericArray();
if (ref.data == nullptr)
{
data = nullptr;
capacity = 0;
return *this;
}
data = new T[ref.capacity];
capacity = ref.capacity;
for (int i = 0; i < capacity; i++)
data[i] = ref.data[i];
return *this;
}
GenericArray(const GenericArray<T> & ref)
{
if (ref.data == nullptr)
{
data = nullptr;
capacity = 0;
return;
}
capacity = ref.capacity;
data = new T[capacity];
for (int i = 0; i < capacity; i++)
data[i] = ref.data[i];
}
int getCapacity() const
{
return capacity;
}
};