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