From 7b19cabee8b08478f31f6e4594ed28e1d04e153c Mon Sep 17 00:00:00 2001 From: Syndamia Date: Fri, 10 May 2024 10:10:21 +0300 Subject: [w11] Solved exercises --- week11/Exercise09/MixedArray.hpp | 107 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 week11/Exercise09/MixedArray.hpp (limited to 'week11/Exercise09/MixedArray.hpp') diff --git a/week11/Exercise09/MixedArray.hpp b/week11/Exercise09/MixedArray.hpp new file mode 100644 index 0000000..096a227 --- /dev/null +++ b/week11/Exercise09/MixedArray.hpp @@ -0,0 +1,107 @@ +#pragma once + +template +class MixedArray { + void free(); + void copyFrom(const MixedArray& other); + +protected: + T* first; + U* second; + unsigned allocated; + unsigned size; + +public: + MixedArray(); + virtual ~MixedArray(); + MixedArray(const MixedArray& other); + MixedArray& operator=(const MixedArray& other); + MixedArray(MixedArray&& other); + MixedArray& operator=(MixedArray&& other); + + void At(int index, T*& valueFirst, U*& valueSecond); + + virtual MixedArray* operator+=(MixedArray* other) = 0; +}; + +template +void MixedArray::free() { + delete[] first; + delete[] second; +} + +template +void MixedArray::copyFrom(const MixedArray& other) { + this->size = other.size; + this->allocated = other.allocated; + first = new T[allocated]; + second = new U[allocated]; + for (int i = 0; i < size; i++) { + first[i] = other.first[i]; + second[i] = other.second[i]; + } +} + +template +MixedArray::MixedArray() { + first = second = nullptr; + size = allocated = 0; +} + +template +MixedArray::~MixedArray() { + free(); +} + +template +MixedArray::MixedArray(const MixedArray& other) { + copyFrom(other); +} + +template +MixedArray& MixedArray::operator=(const MixedArray& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} + +template +MixedArray::MixedArray(MixedArray&& other) { + this->first = other.first; + other.first = nullptr; + this->second = other.second; + other.second = nullptr; + this->allocated = other.allocated; + this->size = other.size; +} + +template +MixedArray& MixedArray::operator=(MixedArray&& other) { + if (this != &other) { + free(); + + this->first = other.first; + other.first = nullptr; + this->second = other.second; + other.second = nullptr; + this->allocated = other.allocated; + this->size = other.size; + } + return *this; +} + +template +void MixedArray::At(int index, T*& valueFirst, U*& valueSecond) { + if (index < 0) throw "Index out of bounds!"; + + if (index % 2 == 0) { + valueFirst = *first[index / 2]; + valueSecond = nullptr; + } + else { + valueFirst = nullptr; + valueSecond = *second[(index - 1) / 2]; + } +} -- cgit v1.2.3