Files
CPP-Stack/include/stack.h

153 lines
3.0 KiB
C++

#ifndef STACK_H
#define STACK_H
#include <cstdint>
#include <expected>
#include <format>
#include <new>
#include <print>
#define DEFAULT_STACK_SIZE 4
enum class StackErr {
ok,
bad_alloc,
empty,
};
template<typename T>
requires std::formattable<T, char>
class Stack {
private:
uint64_t len;
uint64_t cap;
T *data;
public:
Stack();
~Stack();
std::expected<T, StackErr> pop();
std::expected<T, StackErr> peek();
StackErr push(T val);
uint64_t size();
void print();
};
template <typename T>
requires std::formattable<T, char>
uint64_t Stack<T>::size() {
return this->len;
}
template <typename T>
requires std::formattable<T, char>
Stack<T>::Stack() {
this->data = new T[DEFAULT_STACK_SIZE];
this->cap = DEFAULT_STACK_SIZE;
this->len = 0;
}
template <typename T>
requires std::formattable<T, char>
Stack<T>::~Stack() {
delete[] this->data;
}
template <typename T>
requires std::formattable<T, char>
StackErr Stack<T>::push(T value) {
// If not enough space allocate more space
if (this->len >= this->cap) {
uint64_t new_capacity = this->cap * 2;
T *tmp;
try {
tmp = new T[new_capacity];
} catch (const std::bad_alloc& e) {
return StackErr::bad_alloc;
}
for (int i = 0; i < this->len; i++) {
tmp[i] = this->data[i];
}
delete[] this->data;
this->data = tmp;
this->cap = new_capacity;
}
this->data[this->len] = value;
this->len++;
return StackErr::ok;
}
template <typename T>
requires std::formattable<T, char>
std::expected<T, StackErr> Stack<T>::pop() {
if (this->len == 0) {
return std::unexpected(StackErr::empty);
}
T return_val = this->data[this->len - 1];
this->len--;
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;
this->cap = new_capacity;
}
return return_val;
}
template <typename T>
requires std::formattable<T, char>
std::expected<T, StackErr> Stack<T>::peek() {
if (this->len == 0) {
return std::unexpected(StackErr::empty);
}
return this->data[this->len - 1];
}
template <typename T>
requires std::formattable<T, char>
void Stack<T>::print() {
std::println("Stack:");
std::println("Length: {}.", this->len);
std::println("Capacity: {}.", this->cap);
std::println("{:^22}", "Datos");
std::println("{:^22}", "|");
std::println("{:^22}", "v");
for (uint64_t i = 0; i < this->cap; i++) {
if (i < this->len) {
std::println("[{:^20}]", this->data[i]);
} else {
std::println("[{:^20}]", "EMPTY");
}
}
}
#endif // !ST