From 88f15e35713c9632216931d26443dc588238732f Mon Sep 17 00:00:00 2001 From: Syndamia Date: Tue, 7 May 2024 22:17:12 +0300 Subject: [w10] Added rough solutions to ex 1-10 --- week10/Exercise01/Array.hpp | 89 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 week10/Exercise01/Array.hpp (limited to 'week10/Exercise01/Array.hpp') diff --git a/week10/Exercise01/Array.hpp b/week10/Exercise01/Array.hpp new file mode 100644 index 0000000..29a5906 --- /dev/null +++ b/week10/Exercise01/Array.hpp @@ -0,0 +1,89 @@ +#pragma once + +template +class Array { + T* arr; + unsigned size; + unsigned allocated; + + void resize(); + + void free(); + void copyFrom(const Array& other); + +public: + Array(); + ~Array(); + Array(const Array& other); + Array& operator=(const Array& other); + Array(Array&& other); + Array& operator=(Array&& other); +}; + +template +void Array::resize() { + allocated *= 2; + T* biggerArr = new T[allocated]; + for (int i = 0; i < size; i++) { + biggerArr[i] = arr[i]; + } + delete[] arr; + arr = biggerArr; +} + +template +void Array::free() { + delete[] arr; +} + +template +void Array::copyFrom(const Array& other) { + this->size = other.size; + this->allocated = other.allocated; + this->arr = new T[allocated]; + for (int i = 0; i < size; i++) { + this->arr[i] = other.arr[i]; + } +} + +template +Array::Array() { + this->arr = nullptr; + allocated = size = 0; +} + +template +Array::~Array() { + free(); +} + +template +Array::Array(const Array& other) { + copyFrom(other); +} + +template +Array& Array::operator=(const Array& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} + +template +Array::Array(Array&& other) { + this->arr = other.arr; + other.arr = nullptr; +} + +template +Array& Array::operator=(Array&& other) { + if (this != &other) { + free(); + + this->arr = other.arr; + other.arr = nullptr; + } + return *this; +} -- cgit v1.2.3