« Create a Dynamic Array class in C++
Create a class having the functionalities of a dynamic array
1class DynamicArray2{34public:5 int *data;6 int nextIndex;7 int capacity;89 DynamicArray()10 {11 data = new int[5];12 nextIndex = 0;13 capacity = 5;14 }1516 // custom copy constructor17 DynamicArray(DynamicArray const &d)18 {19 // this->data = d.data; // shallow copy2021 // deep copy22 this->data = new int[d.capacity];23 for (int i = 0; i < d.nextIndex; i++)24 {25 this->data[i] = d.data[i];26 }2728 this->nextIndex = d.nextIndex;29 this->capacity = d.capacity;30 }3132 void operator=(DynamicArray const &d)33 {34 this->data = new int[d.capacity];35 for (int i = 0; i < d.nextIndex; i++)36 {37 this->data[i] = d.data[i];38 }3940 this->nextIndex = d.nextIndex;41 this->capacity = d.capacity;42 }4344 void add(int element)45 {46 if (nextIndex == capacity)47 {48 cout << "nextIndex == capacity" << endl;49 int *newData = new int[2 * capacity];50 for (int i = 0; i < capacity; i++)51 {52 newData[i] = data[i];53 }54 delete[] data;55 data = newData;56 capacity *= 2;57 }58 data[nextIndex] = element;59 nextIndex++;60 }6162 int get(int i) const63 {64 if (i < nextIndex)65 {66 return data[i];67 }68 else69 {70 return -1;71 }72 }7374 void add(int element, int index)75 {76 if (index < nextIndex)77 {78 data[index] = element;79 }80 else if (index == nextIndex)81 {82 add(element);83 }84 else85 {86 return;87 }88 }8990 void print() const91 {92 for (int i = 0; i < nextIndex; i++)93 {94 cout << data[i] << " ";95 }96 cout << endl;97 }98};
For full class code to try out the code yourself: