-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamicArrays.cpp
64 lines (54 loc) · 1.13 KB
/
dynamicArrays.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
#include <iostream>
using namespace std;
class DynamicArray {
int *arr;
int capacity;
int length;
public:
DynamicArray(int initialCapacity = 10) {
capacity = initialCapacity;
length = 0;
arr = new int[capacity];
}
~DynamicArray() {
delete[] arr;
}
void insert(int value) {
if (length == capacity) {
resize();
}
arr[length++] = value;
}
void resize() {
capacity *= 2;
int *newArr = new int[capacity];
for (int i = 0; i < length; i++) {
newArr[i] = arr[i];
}
delete[] arr;
arr = newArr;
}
int get(int index) {
if (index < 0 || index >= length) {
throw out_of_range("Index out of range");
}
return arr[index];
}
int size() {
return length;
}
void print() {
for (int i = 0; i < length; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
};
int main() {
DynamicArray arr;
arr.insert(1);
arr.insert(2);
arr.insert(3);
arr.print(); // Output: 1 2 3
return 0;
}