12
12
* When the expression is ended, the number in the stack is the final answer
13
13
*/
14
14
#include < algorithm> // for all_of
15
+ #include < array> // for array
15
16
#include < cassert> // for assert
16
17
#include < iostream> // for io operations
17
18
#include < stack> // for std::stack
18
19
#include < string> // for stof
19
- #include < vector> // for std::vector
20
20
21
21
/* *
22
22
* @namespace others
@@ -80,13 +80,17 @@ void evaluate(float a, float b, const std::string &operation,
80
80
/* *
81
81
* @brief Postfix Evaluation algorithm to compute the value from given input
82
82
* array
83
- * @param input vector of strings consisting of numbers and operations
83
+ * @tparam N number of array size
84
+ * @param input Array of characters consisting of numbers and operations
84
85
* @returns stack[stackTop] returns the top value from the stack
85
86
*/
86
- float postfix_evaluation (const std::vector<std::string> &input) {
87
+ template <std::size_t N>
88
+ float postfix_evaluation (std::array<std::string, N> input) {
87
89
std::stack<float > stack;
90
+ int j = 0 ;
88
91
89
- for (const auto &scan : input) {
92
+ while (j < N) {
93
+ std::string scan = input[j];
90
94
if (is_number (scan)) {
91
95
stack.push (std::stof (scan));
92
96
@@ -98,6 +102,7 @@ float postfix_evaluation(const std::vector<std::string> &input) {
98
102
99
103
evaluate (op1, op2, scan, stack);
100
104
}
105
+ j++;
101
106
}
102
107
103
108
std::cout << stack.top () << " \n " ;
@@ -113,7 +118,7 @@ float postfix_evaluation(const std::vector<std::string> &input) {
113
118
* @returns none
114
119
*/
115
120
static void test_function_1 () {
116
- std::vector <std::string> input = {" 2" , " 3" , " 1" , " *" , " +" , " 9" , " -" };
121
+ std::array <std::string, 7 > input = {" 2" , " 3" , " 1" , " *" , " +" , " 9" , " -" };
117
122
118
123
float answer = others::postfix_expression::postfix_evaluation (input);
119
124
@@ -126,15 +131,15 @@ static void test_function_1() {
126
131
* @returns none
127
132
*/
128
133
static void test_function_2 () {
129
- std::vector <std::string> input = {" 100" , " 200" , " +" , " 2" , " /" ,
130
- " 5" , " *" , " 7" , " +" };
134
+ std::array <std::string, 9 > input = {" 100" , " 200" , " +" , " 2" , " /" ,
135
+ " 5" , " *" , " 7" , " +" };
131
136
float answer = others::postfix_expression::postfix_evaluation (input);
132
137
133
138
assert (answer == 757 );
134
139
}
135
140
136
141
static void test_function_3 () {
137
- std::vector <std::string> input = {
142
+ std::array <std::string, 43 > input = {
138
143
" 1" , " 1" , " 1" , " 1" , " 1" , " 1" , " 1" , " 1" , " 1" , " 1" , " 1" ,
139
144
" 1" , " 1" , " 1" , " 1" , " 1" , " 1" , " 1" , " 1" , " 1" , " 1" , " 1" ,
140
145
" +" , " +" , " +" , " +" , " +" , " +" , " +" , " +" , " +" , " +" , " +" ,
0 commit comments