@@ -77,6 +77,17 @@ void evaluate(float a, float b, const std::string &operation,
77
77
}
78
78
}
79
79
80
+ namespace {
81
+ float remove_from_stack (std::stack<float > &stack) {
82
+ if (stack.empty ()) {
83
+ throw std::invalid_argument (" Not enough operands" );
84
+ }
85
+ const auto res = stack.top ();
86
+ stack.pop ();
87
+ return res;
88
+ }
89
+ } // namespace
90
+
80
91
/* *
81
92
* @brief Postfix Evaluation algorithm to compute the value from given input
82
93
* array
@@ -91,18 +102,18 @@ float postfix_evaluation(const std::vector<std::string> &input) {
91
102
stack.push (std::stof (scan));
92
103
93
104
} else {
94
- const float op2 = stack.top ();
95
- stack.pop ();
96
- const float op1 = stack.top ();
97
- stack.pop ();
105
+ const auto op2 = remove_from_stack (stack);
106
+ const auto op1 = remove_from_stack (stack);
98
107
99
108
evaluate (op1, op2, scan, stack);
100
109
}
101
110
}
102
111
103
- std::cout << stack.top () << " \n " ;
104
-
105
- return stack.top ();
112
+ const auto res = remove_from_stack (stack);
113
+ if (!stack.empty ()) {
114
+ throw std::invalid_argument (" Too many operands" );
115
+ }
116
+ return res;
106
117
}
107
118
} // namespace postfix_expression
108
119
} // namespace others
@@ -144,6 +155,46 @@ static void test_function_3() {
144
155
assert (answer == 22 );
145
156
}
146
157
158
+ static void test_single_input () {
159
+ std::vector<std::string> input = {" 1" };
160
+ float answer = others::postfix_expression::postfix_evaluation (input);
161
+
162
+ assert (answer == 1 );
163
+ }
164
+
165
+ static void test_not_enough_operands () {
166
+ std::vector<std::string> input = {" +" };
167
+ bool throws = false ;
168
+ try {
169
+ others::postfix_expression::postfix_evaluation (input);
170
+ } catch (std::invalid_argument &) {
171
+ throws = true ;
172
+ }
173
+ assert (throws);
174
+ }
175
+
176
+ static void test_not_enough_operands_empty_input () {
177
+ std::vector<std::string> input = {};
178
+ bool throws = false ;
179
+ try {
180
+ others::postfix_expression::postfix_evaluation (input);
181
+ } catch (std::invalid_argument &) {
182
+ throws = true ;
183
+ }
184
+ assert (throws);
185
+ }
186
+
187
+ static void test_too_many_operands () {
188
+ std::vector<std::string> input = {" 1" , " 2" };
189
+ bool throws = false ;
190
+ try {
191
+ others::postfix_expression::postfix_evaluation (input);
192
+ } catch (std::invalid_argument &) {
193
+ throws = true ;
194
+ }
195
+ assert (throws);
196
+ }
197
+
147
198
/* *
148
199
* @brief Main function
149
200
* @returns 0 on exit
@@ -152,6 +203,10 @@ int main() {
152
203
test_function_1 ();
153
204
test_function_2 ();
154
205
test_function_3 ();
206
+ test_single_input ();
207
+ test_not_enough_operands ();
208
+ test_not_enough_operands_empty_input ();
209
+ test_too_many_operands ();
155
210
156
211
std::cout << " \n Test implementations passed!\n " ;
157
212
0 commit comments