From bef155afbaab2bf9b9da5253a7eea45dbb700316 Mon Sep 17 00:00:00 2001 From: Angel Dimitriev Date: Wed, 5 May 2021 02:25:55 +0300 Subject: Added big 4 for queue --- Sem. 09/task2/Queue.hpp | 67 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 60 insertions(+), 7 deletions(-) diff --git a/Sem. 09/task2/Queue.hpp b/Sem. 09/task2/Queue.hpp index 1cc14c3..1f7f854 100644 --- a/Sem. 09/task2/Queue.hpp +++ b/Sem. 09/task2/Queue.hpp @@ -6,19 +6,27 @@ class Queue T* data; size_t capacity; size_t count; - + size_t head; //where to get size_t tail; //last added element; void resize(size_t newCapacity); + + void copyFrom(const Queue& other); + void free(); public: Queue(); + Queue(const Queue& other); + Queue& operator=(const Queue& other); + void enqueue(const T& obj); T dequeue(); size_t getCount(); size_t isEmpty(); + + ~Queue(); }; template @@ -40,9 +48,9 @@ void Queue::enqueue(const T& obj) resize(capacity * 2); if (count != 0) tail++; - + tail %= capacity; //so we don't get an out of range exception - + data[tail] = obj; count++; @@ -53,10 +61,10 @@ T Queue::dequeue() { if (count == 0) throw std::exception("The collection is empty!"); - + T toReturn = data[head]; (++head) %= capacity; - + count--; return toReturn; @@ -81,11 +89,56 @@ void Queue::resize(size_t newCapacity) for (int i = 0, ind = head; i < count; i++, (++ind) %= capacity) newData[i] = data[ind]; - + delete[] data; capacity = newCapacity; data = newData; head = 0; tail = count - 1; -} \ No newline at end of file +} + +template +void Queue::copyFrom(const Queue& other) +{ + data = new T[other.capacity]; + for (int i = 0; i < other.capacity; i++) + data[i] = other.data[i]; + + head = other.head; + tail = other.tail; + + count = other.count; + capacity = other.capacity; + +} + +template +void Queue::free() +{ + delete[] data; +} + +template +Queue::Queue(const Queue& other) +{ + copyFrom(other); + +} + +template +Queue& Queue::operator=(const Queue& other) +{ + if (this != &other) + { + free(); + copyFrom(other); + } + return *this; +} + +template +Queue::~Queue() +{ + free(); +} -- cgit v1.3.1-23-gd82d