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,发现再说吧