7
7
* functionality.
8
8
*/
9
9
10
- #include < cassert> // / For assert
11
- #include < iostream> // / For IO operations
10
+ #include < cassert> // / For assert
11
+ #include < iostream> // / For IO operations
12
+ #include < stdexcept> // / For std::out_of_range
12
13
13
14
/*
14
15
* @namespace
@@ -22,7 +23,7 @@ namespace data_structures {
22
23
template <typename T>
23
24
class Stack {
24
25
private:
25
- T * stack; // /< Pointer to the stack array
26
+ T* stack; // /< Pointer to the stack array
26
27
int stackSize; // /< Maximum size of the stack
27
28
int stackIndex; // /< Index pointing to the top element of the stack
28
29
@@ -59,10 +60,11 @@ class Stack {
59
60
* @brief Pops an element from the stack
60
61
*
61
62
* @return The popped element
63
+ * @throws std::out_of_range if the stack is empty
62
64
*/
63
65
T pop () {
64
66
if (stackIndex == 0 ) {
65
- return T ( );
67
+ throw std::out_of_range ( " Stack is empty " );
66
68
} else {
67
69
return stack[--stackIndex];
68
70
}
@@ -81,25 +83,27 @@ class Stack {
81
83
* @brief Displays the topmost element of the stack
82
84
*
83
85
* @return The topmost element of the stack
86
+ * @throws std::out_of_range if the stack is empty
84
87
*/
85
88
T topmost () const {
86
89
if (stackIndex > 0 ) {
87
90
return stack[stackIndex - 1 ];
88
91
} else {
89
- return T ( );
92
+ throw std::out_of_range ( " Stack is empty " );
90
93
}
91
94
}
92
95
93
96
/* *
94
97
* @brief Displays the bottom element of the stack
95
98
*
96
99
* @return The bottom element of the stack
100
+ * @throws std::out_of_range if the stack is empty
97
101
*/
98
102
T bottom () const {
99
103
if (stackIndex > 0 ) {
100
104
return stack[0 ];
101
105
} else {
102
- return T ( );
106
+ throw std::out_of_range ( " Stack is empty " );
103
107
}
104
108
}
105
109
};
@@ -112,6 +116,7 @@ class Stack {
112
116
static void test () {
113
117
data_structures::Stack<int > stack (5 );
114
118
119
+ // Test push, pop, topmost and bottom operations
115
120
assert (stack.push (10 ) == true );
116
121
assert (stack.push (20 ) == true );
117
122
assert (stack.push (30 ) == true );
@@ -125,6 +130,22 @@ static void test() {
125
130
126
131
assert (stack.topmost () == 20 );
127
132
assert (stack.bottom () == 10 );
133
+
134
+ assert (stack.pop () == 20 );
135
+ assert (stack.pop () == 10 );
136
+
137
+ // Test for exceptions when stack is empty
138
+ try {
139
+ stack.topmost ();
140
+ } catch (const std::out_of_range& e) {
141
+ assert (std::string (e.what ()) == " Stack is empty" );
142
+ }
143
+
144
+ try {
145
+ stack.bottom ();
146
+ } catch (const std::out_of_range& e) {
147
+ assert (std::string (e.what ()) == " Stack is empty" );
148
+ }
128
149
}
129
150
130
151
/* *
0 commit comments