diff --git a/src/data_structure_implement/array/dynamic_array/dynamic_array.cpp b/src/data_structure_implement/array/dynamic_array/dynamic_array.cpp new file mode 100644 index 0000000..148a953 --- /dev/null +++ b/src/data_structure_implement/array/dynamic_array/dynamic_array.cpp @@ -0,0 +1,431 @@ +#include +#include +#include +using namespace std; +class DynamicArray { +public: + DynamicArray(); + ~DynamicArray(); + + void pushBack(int value); + void popBack(); + + int& at(int index); + int& operator[](int index); + + int size() const; + int capacity() const; + bool empty() const; + void clear(); + void reserve(int newCapacity); + void insert(int index, int value); + void erase(int index); + int& front(); + int& back(); + void resize(int newSize); + +private: + int *data; + int current_size; + int current_capacity; + +}; + +DynamicArray::DynamicArray() { + data = nullptr; + current_size = 0; + current_capacity = 0; +} + +DynamicArray::~DynamicArray() { + delete[] data; +} + +void DynamicArray::pushBack(int value) { + if (current_size == current_capacity) { + int newCapacity; + if (current_capacity == 0) { + newCapacity = 1; + } else { + newCapacity = current_capacity * 2; + } + reserve(newCapacity); + } + + data[current_size] = value; + current_size++; +} + +void DynamicArray::popBack() { + if (empty()) { + return; + } + current_size--; +} + +int& DynamicArray::at(int index) { + if (index < 0 || index >= current_size) { + throw out_of_range("index out of range"); + } + return data[index]; +} + +int& DynamicArray::operator[](int index) { + return data[index]; +} + +int DynamicArray::size() const { + return current_size; +} + +int DynamicArray::capacity() const { + return current_capacity; +} + +bool DynamicArray::empty() const { + return current_size == 0; +} + +void DynamicArray::clear() { + current_size= 0; +} + +void DynamicArray::reserve(int newCapacity) { + if (newCapacity < 0) return; + + if(current_capacity >= newCapacity) return; + + int* newData = new int[newCapacity]; + for (int i=0; i current_size || index < 0) { + throw out_of_range("index out of range"); + } + + if (current_size == current_capacity) { + int newCapacity; + if (current_capacity == 0) { + newCapacity = 1; + } else { + newCapacity = current_capacity * 2; + } + reserve(newCapacity); + } + + for (int i=current_size; i>index; i--) { + data[i] = data[i-1]; + } + data[index] = value; + current_size++; +} + +void DynamicArray::erase(int index) { + if (index >= current_size || index < 0) { + throw out_of_range("index out of range"); + } + + for (int i=index; i current_capacity) { + reserve(newSize); + } + + if (newSize > current_capacity) { + reserve(newSize); + } + + if (newSize > current_size) { + for (int i=current_size; i