added push, need testing
This commit is contained in:
@@ -3,6 +3,7 @@
|
|||||||
|
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
#include <expected>
|
#include <expected>
|
||||||
|
#include <new>
|
||||||
|
|
||||||
#define DEFAULT_STACK_SIZE 4
|
#define DEFAULT_STACK_SIZE 4
|
||||||
|
|
||||||
@@ -46,6 +47,31 @@ Stack<T>::~Stack() {
|
|||||||
delete[] this->data;
|
delete[] this->data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
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->data[this->len] = value;
|
||||||
|
this->len++;
|
||||||
|
|
||||||
|
return StackErr::ok;
|
||||||
|
}
|
||||||
|
|
||||||
#endif // !ST
|
#endif // !ST
|
||||||
|
|||||||
Reference in New Issue
Block a user