From 4dd67adfcbc0dc44ce98ed3c45b950f33faca359 Mon Sep 17 00:00:00 2001 From: LaEntropiaa Date: Sun, 15 Mar 2026 21:26:09 -0600 Subject: [PATCH] added pop, need testing --- include/stack.h | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/include/stack.h b/include/stack.h index c1d49e2..de54ecb 100644 --- a/include/stack.h +++ b/include/stack.h @@ -3,6 +3,7 @@ #include #include +#include #include #define DEFAULT_STACK_SIZE 4 @@ -14,6 +15,7 @@ enum class StackErr { }; template +requires std::formattable class Stack { private: uint64_t len; @@ -34,6 +36,7 @@ public: }; template +requires std::formattable Stack::Stack() { Stack new_stack; new_stack.data = new T[DEFAULT_STACK_SIZE]; @@ -43,11 +46,13 @@ Stack::Stack() { } template +requires std::formattable Stack::~Stack() { delete[] this->data; } template +requires std::formattable StackErr Stack::push(T value) { // If not enough space allocate more space if (this->len >= this->cap) { @@ -74,4 +79,34 @@ StackErr Stack::push(T value) { return StackErr::ok; } +template +requires std::formattable +std::expected Stack::pop() { + if (this->len == 0) { + return std::unexpected(StackErr::empty); + } + + T return_val = this->data[this->len - 1]; + + if (this->cap / 4 > this->len) { + uint64_t new_capacity = this->cap / 2; + T *tmp; + + try { + tmp = new T[new_capacity]; + } catch (const std::bad_alloc& e) { + return std::unexpected(StackErr::bad_alloc); + } + + for (int i = 0; i < this->len; i++) { + tmp[i] = this->data[i]; + } + + delete[] this->data; + this->data = tmp; + } + + return std::expected(return_val); +} + #endif // !ST