Skip to content

Commit e741146

Browse files
committed
chore: add std::out_of_range exception and test cases when stack is empty
1 parent 940ac14 commit e741146

File tree

1 file changed

+27
-6
lines changed

1 file changed

+27
-6
lines changed

data_structures/stack_using_array.cpp

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@
77
* functionality.
88
*/
99

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
1213

1314
/*
1415
* @namespace
@@ -22,7 +23,7 @@ namespace data_structures {
2223
template <typename T>
2324
class Stack {
2425
private:
25-
T *stack; ///< Pointer to the stack array
26+
T* stack; ///< Pointer to the stack array
2627
int stackSize; ///< Maximum size of the stack
2728
int stackIndex; ///< Index pointing to the top element of the stack
2829

@@ -59,10 +60,11 @@ class Stack {
5960
* @brief Pops an element from the stack
6061
*
6162
* @return The popped element
63+
* @throws std::out_of_range if the stack is empty
6264
*/
6365
T pop() {
6466
if (stackIndex == 0) {
65-
return T();
67+
throw std::out_of_range("Stack is empty");
6668
} else {
6769
return stack[--stackIndex];
6870
}
@@ -81,25 +83,27 @@ class Stack {
8183
* @brief Displays the topmost element of the stack
8284
*
8385
* @return The topmost element of the stack
86+
* @throws std::out_of_range if the stack is empty
8487
*/
8588
T topmost() const {
8689
if (stackIndex > 0) {
8790
return stack[stackIndex - 1];
8891
} else {
89-
return T();
92+
throw std::out_of_range("Stack is empty");
9093
}
9194
}
9295

9396
/**
9497
* @brief Displays the bottom element of the stack
9598
*
9699
* @return The bottom element of the stack
100+
* @throws std::out_of_range if the stack is empty
97101
*/
98102
T bottom() const {
99103
if (stackIndex > 0) {
100104
return stack[0];
101105
} else {
102-
return T();
106+
throw std::out_of_range("Stack is empty");
103107
}
104108
}
105109
};
@@ -112,6 +116,7 @@ class Stack {
112116
static void test() {
113117
data_structures::Stack<int> stack(5);
114118

119+
// Test push, pop, topmost and bottom operations
115120
assert(stack.push(10) == true);
116121
assert(stack.push(20) == true);
117122
assert(stack.push(30) == true);
@@ -125,6 +130,22 @@ static void test() {
125130

126131
assert(stack.topmost() == 20);
127132
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+
}
128149
}
129150

130151
/**

0 commit comments

Comments
 (0)