From 4993c6468aa07e7c6a006a721fe82aaa4413eede Mon Sep 17 00:00:00 2001 From: angeld55 Date: Tue, 17 May 2022 20:42:42 +0300 Subject: added bar task --- Sem. 11/Examples/Bar/Queue/Queue.hpp | 151 +++++++++++++++++++++++++++++++++++ 1 file changed, 151 insertions(+) create mode 100644 Sem. 11/Examples/Bar/Queue/Queue.hpp (limited to 'Sem. 11/Examples/Bar/Queue') diff --git a/Sem. 11/Examples/Bar/Queue/Queue.hpp b/Sem. 11/Examples/Bar/Queue/Queue.hpp new file mode 100644 index 0000000..5c9af06 --- /dev/null +++ b/Sem. 11/Examples/Bar/Queue/Queue.hpp @@ -0,0 +1,151 @@ +#pragma once +#include +#include +template +class MyQueue +{ + T* data; + size_t capacity; + size_t size; + + size_t get; + size_t put; + + void resize(); + + void copyFrom(const MyQueue& other); + void free(); +public: + MyQueue(); + + MyQueue(const MyQueue& other); + MyQueue& operator=(const MyQueue& other); + + void push(const T& obj); + void push(T&& obj); //позволява и местене + void pop(); + + const T& peek() const; + bool isEmpty() const; + + ~MyQueue(); + +}; + +template +MyQueue::MyQueue() +{ + capacity = 4; + data = new T[capacity]; + size = 0; + get = put = 0; +} + +template +void MyQueue::push(const T& obj) +{ + if (size == capacity) + resize(); + + data[put] = obj; //operator= + (++put) %= capacity; + size++; +} + +template +void MyQueue::push(T&& obj) +{ + if (size == capacity) + resize(); + + data[put] = std::move(obj); //move operator = + (++put) %= capacity; + size++; +} + +template +bool MyQueue::isEmpty() const +{ + return size == 0; +} + + +template +const T& MyQueue::peek() const +{ + if (isEmpty()) + throw std::logic_error("Empty queue!"); + + return data[get]; +} + +template +void MyQueue::pop() +{ + if (isEmpty()) + throw std::logic_error("Empty queue!"); + (++get) %= capacity; + size--; +} + +template +void MyQueue::resize() +{ + T* resizedData = new T[capacity * 2]; + for (size_t i = 0; i < size; i++) + { + resizedData[i] = data[get]; + (++get) %= capacity; + } + capacity *= 2; + delete[] data; + data = resizedData; + get = 0; + put = size; +} + + +template +void MyQueue::copyFrom(const MyQueue& other) +{ + data = new T[other.capacity]; + for (int i = 0; i < other.capacity; i++) + data[i] = other.data[i]; + + get = other.get; + put = other.put; + + size = other.size; + capacity = other.capacity; + +} + +template +void MyQueue::free() +{ + delete[] data; +} + +template +MyQueue::MyQueue(const MyQueue& other) +{ + copyFrom(other); + +} + +template +MyQueue& MyQueue::operator=(const MyQueue& other) +{ + if (this != &other) + { + free(); + copyFrom(other); + } + return *this; +} + +template +MyQueue::~MyQueue() +{ + free(); +} -- cgit v1.3.1-23-gd82d