From 5350b9f4138e70cb00f72999336437e995798244 Mon Sep 17 00:00:00 2001 From: Angeld55 Date: Fri, 20 Sep 2019 15:02:58 +0300 Subject: Update Queue.hpp --- Templates/Queue.hpp | 122 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 121 insertions(+), 1 deletion(-) diff --git a/Templates/Queue.hpp b/Templates/Queue.hpp index 4c559f7..1f5cc18 100644 --- a/Templates/Queue.hpp +++ b/Templates/Queue.hpp @@ -1 +1,121 @@ -j +ifndef QUEUE_HDR +#define QUEUE_HDR + +#include +using namespace std; + +template +class Queue { +private: + T * arr; + int capacity; + int count; + + int whereToPut; + int whereToGet; + void Resize(); + void CopyFrom(const Queue& other); + void Free(); + +public: + Queue(); + Queue(const Queue& other); + Queue& operator=(const Queue& other); + ~Queue(); + + bool isEmpty() const; + void Push(T el); + T Pop(); + T& Peek(); +}; + +template +void Queue::Resize() { + T* temp = new T[capacity * 2]; + for (int i = 0; i < capacity; ++i) + temp[i] = Pop(); + whereToGet = 0; + whereToPut = capacity; + count = capacity; + capacity *= 2; + delete[] arr; + arr = temp; +} + +template +void Queue::CopyFrom(const Queue& other) { + arr = new T[other.capacity]; + for (int i = 0; i < other.count; ++i) + arr[i] = other.arr[i]; + count = other.count; + capacity = other.capacity; + whereToPut = other.whereToPut; + whereToGet = other.whereToGet; +} + +template +void Queue::Free() { + delete[] arr; + count = capacity = 0; +} + +template +Queue::Queue() { + arr = new T[4]; + capacity = 4; + count = 0; + whereToPut = 0; + whereToGet = 0; +} + +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(); +} + +template +bool Queue::isEmpty() const { + return count == 0; +} + +template +void Queue::Push(T el) { + if (count == capacity) + Resize(); + arr[whereToPut] = el; + (whereToPut += 1) %= capacity; + count++; +} + +template +T Queue::Pop() { + if (count == 0) + throw "Queue is empty"; + T elToReturn = arr[whereToGet]; + count--; + (whereToGet += 1) %= capacity; + return elToReturn; +} + +template +T& Queue::Peek() { + if (isEmpty()) + throw std::logic_error("empty queue"); + return arr[whereToGet]; +} + +#endif // !QUEUE_HDR -- cgit v1.3.1-23-gd82d