中缀表达式转后缀表达式并计算

使用vector容器来存储后缀表达式

#include<iostream>
#include<stack>
#include<string>
#include<vector>
#include<unordered_map>
using namespace std;
stack<char> op;//存储运算符
stack<int> num1;//存储数字
vector<string> num;//用来存储后缀表达式
int eval(string s4)
{
	int x, y;
	x = num1.top();
	num1.pop();
	y = num1.top();
	num1.pop();
	if (s4 == "+") return x + y;
	else if (s4 == "-")return x - y;
	else if (s4 == "*") return x * y;
	else if (s4 == "/") return x / y;
}
int main()
{
	//vector<string> num;
	unordered_map<char, int> pr{ {'+',1},{'-',1},{'*',2},{'/',2} };
	string str;
	cin >> str;
	for (int i = 0; i < str.size(); ++i)
	{
		auto c = str[i];
		if (isdigit(c))
		{
			int x = 0, j = i;
			while (j < str.size() && isdigit(str[j]))
				x = x * 10 + str[j++] - '0';
			i = j - 1;
			string s = to_string(x);
			num.push_back(s);
		}
		else if (c == '-' || c == '+' || c == '*' || c == '/')
		{
			while (!op.empty() && pr[c] <= pr[op.top()])//若栈顶元素大于等于新的运算符,则出栈
			{
				string s1 = "";
				s1 = s1 + op.top();
				num.push_back(s1);
				op.pop();
			}
			op.push(c);//进栈
			/*if (op.empty() || pr[c] > pr[op.top()])
			{
				op.push(c);
			}*/
		}
		else if (c == '(')//左括号直接入栈
		{
			op.push(c);
		}
		else if (c == ')')//若是右括号则弹出所有在左括号上面的运算符
		{
			//int j1 = i;
			while (op.top() != '(')
			{
				string s2 = "";
				s2 = s2 + op.top();
				num.push_back(s2);
				op.pop();
			}
			op.pop();
		}

	}
	if (!op.empty())//栈中还存在运算符则移至vector<string>
	{
		while (!op.empty())
		{
			string s3 = "";
			s3 = s3 + op.top();
			num.push_back(s3);
			op.pop();
		}
	}
	//后缀表达式计算
	for (int k = 0; k<num.size(); k++)
	{
			if (num[k].size() > 1)//若是两位以上的数字
			{
				int x1 = 0;
				for (auto c1 : num[k])
				{
					x1 = x1 * 10 + c1 - '0';
				}
				num1.push(x1);
			}
			else //if (num[k] == "-" || num[k] == "+" || num[k] == "*" || num[k] == "/")
			{
				for (auto c2 : num[k])//判断是以为数字还是运算符
				{
					if (isdigit(c2))//若是一位数字
					{
						num1.push(c2-'0');
					}
					else
					{
						num1.push(eval(num[k]));
					}
					break;
				}
				//num1.push(eval(num[k]));
			}
	}
	cout << num1.top();//输出结果
	return 0;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值