-
Notifications
You must be signed in to change notification settings - Fork 0
/
Vector Class.cpp
118 lines (94 loc) · 2.79 KB
/
Vector Class.cpp
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
#include <iostream>
#include <cassert>
template <typename Object>
class Vector {
private:
int m_size;
int m_capacity;
Object* m_ptr;
public:
explicit Vector(int size = 0) : m_size{ size }, m_capacity{ size == 0 ? 1 : size * 2 } {
m_ptr = new Object[m_capacity];
}
~Vector() {
if(m_ptr != nullptr)
delete[] m_ptr;
}
// Copy constructor with deep copying
Vector(const Vector<Object>& a) : m_size{ a.m_size }, m_capacity{ a.m_capacity }, m_ptr{ new Object[a.m_capacity] } {
for (int i = 0; i < m_size; ++i) {
m_ptr[i] = a.m_ptr[i];
}
}
// Copy assignment with deep copying
Vector& operator=(const Vector<Object>& a) {
if (&a == this) return *this;
delete[] m_ptr;
m_size = a.m_size;
m_capacity = a.m_capacity;
m_ptr = new Object[m_capacity];
for (int i = 0; i < m_size; ++i) {
m_ptr[i] = a.m_ptr[i];
}
return *this;
}
// Move copy constructor
Vector(Vector<Object>&& a) noexcept : m_size{ a.m_size }, m_capacity{ a.m_capacity }, m_ptr{ a.m_ptr } {
a.m_ptr = nullptr;
a.m_size = 0;
a.m_capacity = 0;
}
// Move assignment
Vector& operator=(Vector<Object>&& a) noexcept {
if (&a == this) return *this;
delete[] m_ptr;
m_size = a.m_size;
m_capacity = a.m_capacity;
m_ptr = a.m_ptr;
a.m_ptr = nullptr;
a.m_size = 0;
a.m_capacity = 0;
return *this;
}
void reserve(int newCapacity) {
if (newCapacity <= m_size) return;
Object* newObject = new Object[newCapacity];
for (int i = 0; i < m_size; ++i) {
newObject[i] = std::move(m_ptr[i]);
}
m_capacity = newCapacity;
std::swap(m_ptr, newObject);
delete[] newObject;
}
void resize(int newSize) {
if (newSize > m_capacity)
reserve(newSize * 2);
m_size = newSize;
}
void push_back(const Object& obj) {
if (m_size == m_capacity)
reserve(2 * m_capacity);
m_ptr[m_size++] = obj;
}
void pop_back() {
assert(m_size > 0); // Check if vector is not empty
--m_size;
}
Object& operator[](int index) {
assert(index >= 0 && index < m_size); // Range check
return m_ptr[index];
}
const Object& operator[](int index) const {
assert(index >= 0 && index < m_size); // Range check
return m_ptr[index];
}
int size() const {
return m_size;
}
int capacity() const {
return m_capacity;
}
bool empty() const {
return m_size == 0;
}
};