数据结构---中缀转后缀计算表达式计算结果(支持括号)

0.简介

有了上一篇的基础,我直接在上面修改支持括号,主要就是将括号里面的式子单独拿出来,在递归计算结果。

1.实现

#include<iostream>
#include<string>
#include<vector>
#include<unordered_map>
#include<stack>
#include<functional>
using namespace std;
unordered_map<string, pair<int, function<void(float&, float)>>> ops =
{ {"+",{1,[](float& a,float b) {a += b; }}},{"-",{1,[](float& a,float b) {a -= b; }}},
  {"*",{2,[](float& a,float b) {a *= b; }}},{"/",{2,[](float& a,float b) {a /= b; }}} };
float calcStr(const string& s)
{
	vector<float> arr;
	stack<char> st;
	int i = 0, j = 0, count=0;
	while ((j = i) < s.size() || !st.empty())
	{
		while ((s[i] >= '0' && s[i] <= '9')||s[i]=='.')i++;//捕获数字
		if (i > j)
			arr.push_back(atof(s.substr(j, i - j).c_str()));
		if (s[j = i] == '(')//这里直接递归,去掉一层括号
		{
			count = 0;
			while ((s[i++] == '(' ? ++count : (s[i] == ')' ? --count : 1)));
			arr.push_back(calcStr(s.substr(j + 1, (i++) - j - 1)));
			//continue;
		}
		if (st.empty() && s[i]!='\0' || (ops.find(string(1, s[i])) != ops.end() && ops[string(1, s[i])].first > ops[string(1, st.top())].first))
			st.push(s[i++]);//这里对符号进行处理,所有入栈情况都在这里
		else//反之就是出栈情况
			while (!st.empty() && !(s[i] != '\0' && ops[string(1, s[i])].first > ops[string(1, st.top())].first))//栈空了或者前一个符号优先级低就退出
			{
				ops[string(1, st.top())].second(arr[arr.size() - 2], arr[arr.size() - 1]);
				arr.pop_back();
				st.pop();
			}
	}
	return arr[0];
}

int main()
{

	string s = "(2.3+2*((1+2)*(2-1))*2+2*(2+2))*2+2*8/4";// "1+1*1+6*2/3*2+1*2-2+2*1+1+1+1/2";
	cout << calcStr(s) << endl;
	return 0;
}

有可能有啥BUG,发现再说吧

上一篇:中缀转后缀计算

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值