-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathSimpleVector.h
119 lines (97 loc) · 2.28 KB
/
SimpleVector.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
115
116
117
118
119
#ifndef SIMPLEVECTOR_H
#define SIMPLEVECTOR_H
#include <iostream>
#include <cstdlib>
template <class T>
class SimpleVector
{
private:
// array pointer
T *arrPtr {nullptr};
// number of elements
int arraySize {0};
// handles subscripts out of range
void subscriptError();
public:
// default constructor
SimpleVector() = default;
// constructor
SimpleVector(int);
// copy constructor
SimpleVector(const SimpleVector&);
// copy assignment
SimpleVector& operator=(const SimpleVector&);
// destructordeclaration
~SimpleVector();
// array size accessor
int size() const
{
return arraySize;
}
// accessor to return a specific element
T getElementAt(int position);
// overloaded [] operator declaration
T &operator[](const int&);
};
template <class T>
SimpleVector<T>::SimpleVector(int s) : arraySize(s), arrPtr(new T[s])
{
// initialize the array
for (int i = 0; i < arraySize; i++)
{
arrPtr[i] = 0;
}
}
template <class T>
SimpleVector<T>::SimpleVector(const SimpleVector &obj) : arraySize(obj.arraySize), arrPtr(new T[obj.arraySize])
{
// copy the elements of source array
for (int i = 0; i < arraySize; i++)
{
arrPtr[i] = obj.arrPtr[i];
}
}
template<class T>
SimpleVector<T>& SimpleVector<T>::operator=(const SimpleVector<T>& other)
{
delete [] arrPtr;
// copy the array size
arraySize = other.arraySize;
// allocate memory for the array
arrPtr = new T[arraySize];
// copy the elements of source array
for (int i = 0; i < arraySize; i++)
{
arrPtr[i] = other.arrPtr[i];
}
return *this;
}
template <class T>
SimpleVector<T>::~SimpleVector()
{
delete [] arrPtr;
}
template <class T>
void SimpleVector<T>::subscriptError()
{
throw "ERROR: Subscript out of range.";
}
template <class T>
T SimpleVector<T>::getElementAt(int sub)
{
if (sub < 0 || sub >= arraySize)
{
subscriptError();
}
return arrPtr[sub];
}
template <class T>
T &SimpleVector<T>::operator[](const int& sub)
{
if (sub < 0 || sub >= arraySize)
{
subscriptError();
}
return arrPtr[sub];
}
#endif