From 72300056a10209e483e7e499c7f03c207924bb82 Mon Sep 17 00:00:00 2001 From: Angel Dimitriev Date: Wed, 11 May 2022 13:17:28 -0400 Subject: Create kPriorityQueue.hpp --- Sem. 10/Examples/kPriorityQueue.hpp | 134 ++++++++++++++++++++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 Sem. 10/Examples/kPriorityQueue.hpp diff --git a/Sem. 10/Examples/kPriorityQueue.hpp b/Sem. 10/Examples/kPriorityQueue.hpp new file mode 100644 index 0000000..9cc7494 --- /dev/null +++ b/Sem. 10/Examples/kPriorityQueue.hpp @@ -0,0 +1,134 @@ +#include +#include "Queue.hpp" +#include +#ifndef K_PRIORITY_QUEUE +#define K_PRIORITY_QUEUE + +template +class kPriorityQueue +{ + size_t maxPriority; + MyQueue* queues; + void free(); + void copyFrom(const kPriorityQueue &other); + + size_t elementsCount = 0; + +public: + kPriorityQueue(size_t maxPriority); + kPriorityQueue(const kPriorityQueue& other); + kPriorityQueue& operator=(const kPriorityQueue& other); + ~kPriorityQueue(); + + void push(const T& obj, size_t priority); + void push(T&& obj, size_t priority); + void pop(); + + const T& peek() const; + bool isEmpty() const; + +}; + +template +void kPriorityQueue::free() +{ + delete[] queues; +} + +template +void kPriorityQueue::copyFrom(const kPriorityQueue &other) +{ + this->maxPriority = maxPriority; + queues = new MyQueue[maxPriority]; + for (size_t i = 0; i < maxPriority; i++) + queues[i] = other.queues[i]; +} + +template +kPriorityQueue::kPriorityQueue(size_t maxPriority) +{ + if (maxPriority == 0) + throw std::logic_error("Cannot create priority queue with no priorities"); + + this->maxPriority = maxPriority; + queues = new MyQueue[maxPriority]; +} + +template +kPriorityQueue::kPriorityQueue(const kPriorityQueue &other) +{ + copyFrom(); +} + +template +kPriorityQueue &kPriorityQueue::operator=(const kPriorityQueue &other) +{ + if (this != &other) + { + free(); + copyFrom(other); + } + return *this; +} + +template +kPriorityQueue::~kPriorityQueue() +{ + free(); +} + +template +void kPriorityQueue::push(const T &obj, size_t priority) +{ + if (priority >= maxPriority) + throw std::logic_error("No such priority"); + elementsCount++; + queues[priority].push(obj); +} + +template +void kPriorityQueue::push(T &&obj, size_t priority) +{ + if (priority >= maxPriority) + throw std::logic_error("No such priority"); + elementsCount++; + queues[priority].push(std::move(obj)); +} + +template +void kPriorityQueue::pop() +{ + + if(isEmpty()) + throw std::logic_error("Empty queue!"); + + for (int i = maxPriority - 1; i >= 0; i--) + { + if (!queues[i].isEmpty()) + { + queues[i].pop(); + elementsCount--; + return; + } + } +} + +template +const T &kPriorityQueue::peek() const +{ + + for (int i = maxPriority - 1; i >= 0; i--) + { + if (!queues[i].isEmpty()) + return queues[i].peek(); + } + +} + +template +bool kPriorityQueue::isEmpty() const +{ + return elementsCount == 0; +} + +#endif -- cgit v1.3.1-23-gd82d