/
vladlevin790
/
cpp-lab-2
Обзор
Документация
Войти
/
vladlevin790
/
cpp-lab-2
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
src/structures/MyQueue.hpp
124 строки
2 KB
vladlevin790
init
05 май 2026, 21:32
05 май 2026, 21:32
3310cbd
Код
Авторство
О чём код?
#ifndef MyQueue_hpp #define MyQueue_hpp #include <new> #include "IDataStructure.hpp" template <typename T> class MyQueue final : public IDataStructure<T> { private: T* data = nullptr; int head = 0; int tail = 0; int count = 0; int currentCapacity = 0; int physicalIndex(int logicalIndex) const { return (head + logicalIndex) % currentCapacity; } bool grow() { int newCapacity = currentCapacity == 0 ? 4 : currentCapacity * 2; T* newData = nullptr; try { newData = new T[newCapacity]; } catch (const std::bad_alloc&) { return false; } for (int i = 0; i < count; i++) { newData[i] = data[physicalIndex(i)]; } delete[] data; data = newData; currentCapacity = newCapacity; head = 0; tail = count; return true; } public: MyQueue() { grow(); } ~MyQueue() override { delete[] data; } MyQueue(const MyQueue&) = delete; MyQueue& operator=(const MyQueue&) = delete; bool insert(const T& value) override { if (count >= currentCapacity) { if (!grow()) { return false; } } data[tail] = value; tail = (tail + 1) % currentCapacity; count++; return true; } bool removeLast() override { if (count <= 0) { return false; } head = (head + 1) % currentCapacity; count--; if (count == 0) { head = 0; tail = 0; } return true; } bool replaceAt(int index, const T& value) override { if (index < 0 || index >= count) { return false; } data[physicalIndex(index)] = value; return true; } bool tryGet(int index, T& outValue) const override { if (index < 0 || index >= count) { return false; } outValue = data[physicalIndex(index)]; return true; } int size() const override { return count; } int capacity() const override { return currentCapacity; } void clear() override { head = 0; tail = 0; count = 0; } const char* name() const override { return "Queue"; } }; #endif