-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVector.cpp
More file actions
71 lines (60 loc) · 1.38 KB
/
Copy pathVector.cpp
File metadata and controls
71 lines (60 loc) · 1.38 KB
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
#include "Vector.h"
#include <stdexcept>
using namespace std;
template <typename T>
void Vector<T>::resize() {
int newCapacity = capacity * 2;
T* newArr = new T[newCapacity];
for (int i = 0; i < length; i++) {
newArr[i] = arr[i];
}
delete[] arr;
arr = newArr;
capacity = newCapacity;
}
template <typename T>
Vector<T>::Vector(int initialCapacity) {
capacity = initialCapacity;
length = 0;
arr = new T[capacity];
}
template <typename T>
Vector<T>::~Vector() {
delete[] arr;
}
template <typename T>
void Vector<T>::push_back(T value) {
if (length == capacity)
resize();
arr[length++] = value;
}
template <typename T>
void Vector<T>::pop_back() {
if (length == 0)
throw std::runtime_error("Vector is empty");
length--;
}
template <typename T>
T& Vector<T>::operator[](int index) {
if (index < 0 || index >= length)
throw std::runtime_error("Index out of range");
return arr[index];
}
template <typename T>
int Vector<T>::size() const {
return length;
}
template <typename T>
bool Vector<T>::empty() const {
return length == 0;
}
template <typename T>
T& Vector<T>::back() {
if (empty())
throw std::runtime_error("Vector is empty");
return arr[length - 1];
}
template class Vector<int>;
template class Vector<char>;
template class Vector<float>;
template class Vector<double>;