Neat Vectors  5
Hanes
vector.hpp
1 // Constructor
2 template<class FUN>
4 {
5  sz = 4;
6  max = 0;
7  array = new FUN[4];
8 }
9 
10 // Copy Constructor
11 template<class FUN>
13 {
14  sz = v.sz;
15  max = v.max;
16  array = new FUN[sz];
17  for(unsigned int i = 0; i < max; i++)
18  {
19  array[i] = v.array[i];
20  }
21 }
22 
23 // Destructor
24 template<class FUN>
26 {
27  delete [] array;
28 }
29 
30 // Add elements to the vector
31 template<class FUN>
33 {
34  // Expand vector if needed
35  if(max == sz)
36  {
37  sz = sz * 2;
38  FUN* new_array = new FUN[sz];
39  for(unsigned int i = 0; i < max; i++)
40  {
41  new_array[i] = array[i];
42  }
43 
44  delete[] array;
45  array = new_array;
46  }
47 
48  array[max] = v;
49  max++;
50 }
51 
52 // Read elements of the vector
53 template<class FUN>
54 FUN& Vector<FUN>::operator[](const unsigned int idx)
55 {
56  if(idx < 0 || idx >= max)
57  {
58  throw invalid_argument("Index out of range");
59  }
60 
61  return array[idx];
62 }
63 
64 // Read elements of the vector
65 template<class FUN>
66 const FUN& Vector<FUN>::operator[](const unsigned int idx) const
67 {
68  if(idx < 0 || idx >= max)
69  {
70  throw invalid_argument("Index out of range");
71  }
72 
73  return array[idx];
74 }
75 
76 // length getter
77 template<class FUN>
78 unsigned int Vector<FUN>::length() const
79 {
80  return max;
81 }
82 
83 // size getter
84 template<class FUN>
85 unsigned int Vector<FUN>::size() const
86 {
87  return sz;
88 }
89 
90 template<class FUN>
91 ostream& operator<<(ostream& out, const Vector<FUN>& v)
92 {
93  out << "[";
94 
95  // if v.size() == 0 then v.size() - 1 underflows
96  if(v.length() > 0)
97  {
98  for(unsigned int i = 0; i < v.length() - 1; i++)
99  {
100  out << v[i] << ", ";
101  }
102  out << v[v.length() - 1];
103  }
104 
105  out << "]";
106  return out;
107 }
Vector()
Constructs an empty vector.
Definition: vector.hpp:3
A (very neat) vector.
Definition: vector.h:37
FUN & operator[](const unsigned int idx)
Reads an element of the vector.
Definition: vector.hpp:54
unsigned int size() const
The size of the underlying storage.
Definition: vector.hpp:85
unsigned int length() const
The number of items stored in the vector.
Definition: vector.hpp:78
~Vector()
Destructor.
Definition: vector.hpp:25
void push_back(FUN v)
Add elements to the vector.
Definition: vector.hpp:32