DSC Engine
Loading...
Searching...
No Matches
stack.hpp
Go to the documentation of this file.
1
6#pragma once
7
8#include "DSCEngine/debug/error.hpp"
9
10namespace DSC
11{
12 template<typename T> class Stack
13 {
14 private:
15 struct Item
16 {
17 T value;
18 Item* next;
19 };
20 Item* top_item = nullptr;
21 public:
22 Stack() = default;
23 Stack(Stack<T>&& stack);
24 Stack<T>& operator = (Stack<T>&& stack);
25
29 void clear();
30
36 bool is_empty() const;
37
43 void push(const T& value);
44
50 T pop();
51
52 ~Stack();
53
77 static Stack<T> from_range(const T& a, const T& b, const T& step);
78 };
79}
80
81template<typename T>
83{
84 top_item = stack.top_item;
85 stack.top_item = nullptr;
86}
87
88template<typename T>
90{
91 top_item = stack.top_item;
92 stack.top_item = nullptr;
93 return *this;
94}
95
96template<typename T>
98{
99 return top_item == nullptr;
100}
101
102template<typename T>
103void DSC::Stack<T>::push(const T& value)
104{
105 Item* item = new Item();
106 item->value = value;
107 item->next = top_item;
108 top_item = item;
109}
110
111template<typename T>
113{
114 nds_assert(top_item!=nullptr, "Cannot perform pop on an empty stack");
115 Item* item = top_item;
116 T value = item->value;
117 top_item = top_item->next;
118 delete item;
119 callstack_ret value;
120
121}
122
123template<typename T>
125{
126 clear();
127}
128
129template<typename T>
131{
132 while(top_item!=nullptr)
133 pop();
134}
135
136template<typename T>
137DSC::Stack<T> DSC::Stack<T>::from_range(const T& a, const T& b, const T& step) \
138{
140 T Z = T(); // 0
141 if(step>Z)
142 {
143 nds_assert(a<=b);
144 for(T i=a;i<b;i+=step)
145 s.push(i);
146 }
147 else if(step<Z)
148 {
149 nds_assert(a>=b);
150 for(T i=a;i>b;i+=step)
151 s.push(i);
152 }
153 return s;
154}
Definition: stack.hpp:13
void push(const T &value)
Adds an element at the top of the stack.
Definition: stack.hpp:103
bool is_empty() const
Checks if the stack is empty.
Definition: stack.hpp:97
static Stack< T > from_range(const T &a, const T &b, const T &step)
Creates a stack from all elements ranging between certain values.
Definition: stack.hpp:137
void clear()
Clears the stack.
Definition: stack.hpp:130
T pop()
Removes the element at the top of the stack.
Definition: stack.hpp:112