-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6_1.cpp
More file actions
115 lines (98 loc) · 2.11 KB
/
6_1.cpp
File metadata and controls
115 lines (98 loc) · 2.11 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
#include <iostream>
using namespace std;
class DynamicArray
{
private:
int *data;
int size;
int capacity;
void resize(int newCapacity)
{
int *newData = new int[newCapacity];
for (int i = 0; i < size; i++)
{
newData[i] = data[i];
}
delete[] data;
data = newData;
capacity = newCapacity;
}
public:
DynamicArray(int initialCapacity = 4)
{
data = new int[initialCapacity];
size = 0;
capacity = initialCapacity;
}
~DynamicArray()
{
delete[] data;
}
void append(int value)
{
if (size == capacity)
{
resize(capacity * 2);
}
data[size++] = value;
}
void removeAt(int index)
{
if (index < 0 || index >= size)
{
cout << "Index out of bounds.\n";
return;
}
for (int i = index; i < size - 1; i++)
{
data[i] = data[i + 1];
}
size--;
if (size > 0 && size <= capacity / 4)
{
resize(capacity / 2);
}
}
int get(int index) const
{
if (index < 0 || index >= size)
{
cout << "Index out of bounds.\n";
return -1;
}
return data[index];
}
int getSize() const
{
return size;
}
void print() const
{
cout << "[ ";
for (int i = 0; i < size; i++)
{
cout << data[i] << " ";
}
cout << "]\n";
}
};
int main()
{
DynamicArray arr;
arr.append(5);
arr.append(10);
arr.append(15);
arr.append(20);
arr.append(25);
cout << "Array after appending elements: ";
arr.print();
arr.removeAt(1);
cout << "After removing index 2 :: ";
arr.print();
cout << "Element at index 1 :: " << arr.get(1) << endl;
arr.append(40);
cout << "After appending 40 :: ";
arr.print();
cout<<endl<<"24CE052_Pushti"<<endl;
return 0;
}