added pop, need testing
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
|
||||
#include <cstdint>
|
||||
#include <expected>
|
||||
#include <format>
|
||||
#include <new>
|
||||
|
||||
#define DEFAULT_STACK_SIZE 4
|
||||
@@ -14,6 +15,7 @@ enum class StackErr {
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
requires std::formattable<T, char>
|
||||
class Stack {
|
||||
private:
|
||||
uint64_t len;
|
||||
@@ -34,6 +36,7 @@ public:
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
requires std::formattable<T, char>
|
||||
Stack<T>::Stack() {
|
||||
Stack<T> new_stack;
|
||||
new_stack.data = new T[DEFAULT_STACK_SIZE];
|
||||
@@ -43,11 +46,13 @@ Stack<T>::Stack() {
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -74,4 +79,34 @@ StackErr Stack<T>::push(T value) {
|
||||
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];
|
||||
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user