核心代码与思路:
int GetExprValue(vector<string> srcVec) //根据后缀表达式求值
{
stack<int> temp;
char op = '\0';
int a = 0;
int b = 0;
for (int i = 0; i < srcVec.size(); i++) {
op = srcVec[i][srcVec[i].length() - 1];
if (isdigit(op)) {
temp.push(atoi(srcVec[i].c_str())); //如果是数字则直接入栈
} else {
a = temp.top(); //否则从栈中取出两个操作数进行计算(注意操作数的左右顺序)
temp.pop(); //然后将计算的值入栈
b = temp.top();
temp.pop();
temp.push(CalFunc(b, op, a));
}
}
return temp.top();
}
vector<string> GetSufix(string src)
{
vector<string> dest;
stack<char> opStack;
int i = 0;
string temp = "";
while (i < src.length()) {
if (isdigit(src[i])) {
//如果遇到数字就读取一个操作数加入后缀表达式中,注意是引用传递
dest.push_back(ReadIntNum(src, i));
i--; //由于后面会进行++操作,这里要保持在读到的最后一个数字位上
} else if (IsLeftBrac(src[i])) {
//如果遇到左括号直接入栈
opStack.push(src[i]);
} else if (IsRightBrac(src[i])) {
//如果遇到右括号将栈顶元素出栈,加入后缀表达式,直到遇到左括号,将这个左括号弹出
while (opStack.top()!= MatchBrac(