我试图掌握后缀表达式的概念,我尝试寻求帮助,但我看到的所有地方似乎都在使用常规字符串计算后缀表达式;但是我需要能够用数组来做到这一点
#include <string>
#include <stack>
#include <math.h>
using namespace std;
int calculatePostfixExpression(string expression[], int length)
{
stack <int> stack;
// loop to iterate through the expression
for (int i = 0; i < length; i++)
{
// if the character is an operand we push it in the stack
// we have considered single digits only here
if ( expression[i] >= "0" && expression[i] <= "9")
/*compiler error: no operator "-" matches these operands*/
{ stack.push( expression[i] - "0"); }
else
{
// pop the top two elements from the stack
int int1 = stack.top();
stack.pop();
int int2 = stack.top();
stack.pop();
/*compiler error: expression must have integral or enum type*/
switch (expression[i])
{
/*compiler error for all cases: this constant has type "const char*" instead of the required "std::string" type*/
case "+": // addition
stack.push(int2 + int1);
break;
case "-": // subtraction
stack.push(int2 - int1);
break;
case "*": // multiplication
stack.push(int2 * int1);
break;
case "/": // division
stack.push(int2 / int1);
break;
case "%": // exponent
stack.push(int2 % int1);
break;
}
}
}
return stack.top();
}
我找不到任何地方似乎使用堆栈和字符串数组来做后缀表达式,但提示告诉我使用数组