-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataStructures.h
More file actions
149 lines (114 loc) · 2.83 KB
/
Copy pathdataStructures.h
File metadata and controls
149 lines (114 loc) · 2.83 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#pragma once
#include <stdexcept>
template<typename T>
struct myVector {
private:
size_t arr_size;
size_t arr_capacity;
T* data;
public:
myVector() {
arr_size = 0;
arr_capacity = 1;
data = new T[1];
}
myVector(int Capacity, T default_value) {
arr_size = Capacity;
arr_capacity = Capacity;
data = new T[arr_capacity];
for (int i = 0; i < arr_capacity; i++) {
data[i] = default_value;
}
}
// Copy constructor.
myVector(const myVector& other) {
arr_size = other.arr_size;
arr_capacity = other.arr_capacity;
data = new T[arr_capacity];
for (int i = 0; i < arr_size; i++) {
data[i] = other.data[i];
}
}
// Copy assignment operator.
myVector& operator=(const myVector& other) {
if (this != &other) {
arr_size = other.arr_size;
arr_capacity = other.arr_capacity;
delete[] data;
data = new T[arr_capacity];
for (int i = 0; i < arr_size; i++) {
data[i] = other.data[i];
}
}
return *this;
}
void push_back(T element) {
if (arr_size == arr_capacity) {
arr_capacity *= 2;
T* new_data = new T[arr_capacity];
for (size_t i = 0; i < arr_size; i++) {
new_data[i] = data[i];
}
delete[] data;
data = new_data;
}
data[arr_size] = element;
arr_size++;
}
void resize(int newCapacity) {
T* new_data = new T[newCapacity];
for (int i = 0; i < arr_size; i++) {
new_data[i] = data[i];
}
delete[] data;
data = new_data;
arr_capacity = newCapacity;
arr_size = newCapacity;
}
void pop_back() {
if (arr_size > 0) {
arr_size--;
}
else {
throw std::runtime_error("Vector is empty. cannot pop back from vector.");
}
}
size_t size() {
return arr_size;
}
size_t capacity() {
return arr_capacity;
}
void clear() {
arr_size = 0;
}
bool empty() {
return arr_size == 0;
}
~myVector() {
delete[] data;
data = nullptr;
}
T& operator[](int index) {
if (index >= 0 && index < arr_size) {
return data[index];
}
else {
throw std::out_of_range("Index out of range.");
}
}
};
template<typename T1, typename T2>
struct myPair {
T1 first;
T2 second;
myPair() {}
myPair(T1 F, T2 S) {
first = F;
second = S;
}
bool operator==(const myPair& other) {
if (first == other.first && second == other.second) return true;
else return false;
}
};