表达式求值是栈的一个重要的应用。例如计算器中的加减乘除的表达式计算,都会使用栈来进行求值。下面的代码只用两个栈便实现了表达式求值的功能。但由于是C++,还有很多地方不熟悉,主要还是在于观摩学习
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
#include <unordered_map>
using namespace std;
stack<int> num;
stack<char> op;
void eval()
{
auto b = num.top();
num.pop();
auto a = num.top();
num.pop();
auto c = op.top();
op.pop();
int x;
if (c == '+') x = a + b;
else if (c == '-') x = a - b;
else if (c == '*') x = a * b;
else x = a / b;
num.push(x);
}
int main()
{
unordered_map<char, int> pr{
{'+', 1}, {'-', 1}, {'*&#