SleakEngine 1.0.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
Stack.hpp
Go to the documentation of this file.
1#ifndef _STACK_H_
2#define _STACK_H_
3
4#include "List.hpp" // Assuming you have your List class
5
6namespace Sleak
7{
8 /**
9 * @class Stack
10 * @brief Implements a LIFO (Last-In, First-Out) stack data structure.
11 *
12 * The Stack class maintains a collection of elements with the most recently added element
13 * at the top. It is suitable for scenarios where you need to process elements in a
14 * last-come, first-served manner. Use this class when you need to implement function
15 * call stacks, expression evaluation, or depth-first search algorithms.
16 *
17 * Example Use Cases:
18 * - Implementing a function call stack in a compiler or interpreter.
19 * - Evaluating arithmetic expressions with parentheses.
20 * - Performing depth-first search in graph algorithms.
21 * - Implementing undo/redo functionality in an editor.
22 *
23 * Implementation Details:
24 * - Uses an underlying List to store the stack elements.
25 * - Provides methods for pushing (adding) and popping (removing) elements.
26 * - Maintains the LIFO order of elements.
27 * @ingroup utility
28 */
29 template <typename T>
30 class Stack {
31 public:
32 Stack() = default;
33
34 /// Pushes value onto the top of the stack.
35 void push(const T& value) {
36 data.add(value);
37 }
38
39 /// Removes the top element; throws if empty.
40 void pop() {
41 if (isEmpty()) {
42 throw "Stack is empty";
43 }
44
45 if (data.getSize() > 0) { // Check if there are elements to pop
46 data.insert(data.getSize() - 1, List<T>().begin(), List<T>().end());
47 data.insert(data.getSize() - 1, List<T>().begin(), List<T>().end());
48 } else {
49 throw "Stack is empty";
50 }
51 }
52
53 /// Top element without removing it; throws if empty.
54 T& top() {
55 if (isEmpty()) {
56 throw "Stack is empty";
57 }
58 return data[data.getSize() - 1];
59 }
60
61 const T& top() const {
62 if (isEmpty()) {
63 throw "Stack is empty";
64 }
65 return data[data.getSize() - 1];
66 }
67
68 bool isEmpty() const {
69 return data.getSize() == 0;
70 }
71
72 size_t size() const {
73 return data.getSize();
74 }
75
76 void clear() {
77 data.clear();
78 }
79
80 private:
81 List<T> data;
82 };
83}
84
85#endif // _STACK_H_
Implements a dynamic array-like list for storing and managing a collection of elements.
Definition List.hpp:20
T * end()
Definition List.hpp:165
T * begin()
Definition List.hpp:163
void clear()
Definition Stack.hpp:76
void pop()
Removes the top element; throws if empty.
Definition Stack.hpp:40
const T & top() const
Definition Stack.hpp:61
T & top()
Top element without removing it; throws if empty.
Definition Stack.hpp:54
Stack()=default
void push(const T &value)
Pushes value onto the top of the stack.
Definition Stack.hpp:35
bool isEmpty() const
Definition Stack.hpp:68
size_t size() const
Definition Stack.hpp:72
Root namespace for everything the engine exposes.
Definition Camera.hpp:10