-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathVector.cpp
More file actions
107 lines (91 loc) · 1.75 KB
/
Vector.cpp
File metadata and controls
107 lines (91 loc) · 1.75 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
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
#include "Vector.h"
template<typename T>
void Vector<T>::expand(int newCapacity) {
if (newCapacity <= SIZE) return;
T* tmp = new T[SIZE];
for (int i = 0; i < SIZE; i++) {
tmp[i] = arr[i];
}
delete[]arr;
arr = new T[newCapacity];
for (int i = 0; i < SIZE; i++) {
arr[i] = tmp[i];
}
delete[] tmp;
capacity = newCapacity;
}
template<typename T>
Vector<T>::Vector() {
int size = 0;
capacity = 100;
arr = new T[capacity];
}
template<typename T>
Vector<T>::Vector(int initCapacity) {
int size = 0;
capacity = initCapacity;
arr = new T[capacity];
}
template<typename T>
Vector<T>::~Vector() {
delete[] arr;
}
template<typename T>
int Vector<T>::size()const {
return SIZE;
}
template<typename T>
bool Vector<T>::empty() {
return SIZE == 0;
}
template<typename T>
void Vector<T>::push_back(const T& newElement) {
if (SIZE == capacity) {
expand(capacity + capacity / 2);
}
arr[SIZE] = newElement;
SIZE++;
}
template<typename T>
void Vector<T>::pop_back() {
SIZE--;
}
template<typename T>
void Vector<T>::insert(int pos, const T& newElement) {
if (SIZE == capacity) {
expand(capacity + capacity / 2);
}
for (int i = SIZE; i > pos; i--) {
arr[i] = arr[i - 1];
}
arr[pos] = newElement;
SIZE++;
}
template<typename T>
void Vector<T>::erase(int pos) {
for (int i = pos; i < SIZE; i++) {
arr[i] = arr[i + 1];
}
SIZE--;
}
template<typename T>
void Vector<T>::clearn() {
SIZE = 0;
}
template<typename T>
Vector<T>& Vector<T>::operator=(const Vector<T>& rhs) {
if (this != &rhs) {
delete[] arr;
this->SIZE = rhs.SIZE;
this->capacity = rhs.capacity;
this->arr = new T[capacity];
for (int i = 0; i < SIZE; i++) {
arr[i] = rhs.arr[i];
}
}
return *this;
}
template<typename T>
T& Vector<T>::operator[](int idx) const {
return arr[idx];
}