#include<iostream>
using namespace std;
#include<unordered_map>
#include<string>
#include<stack>
#include<map>
#include<vector>
bool priority(char op1,char top)
{
std::map<char, int>arr_={
{'*',1},
{'/',1},
{'+',0},
{'-',0},
{'(',-1},
{')',-1},
{'(',-1},
{')',-1}
};
return arr_[op1] > arr_[top];
}
std::vector<char> postfix(string my_cin)
{
std::stack<char>_operator;
std::vector<char>postfix_notion;
for (std::string::iterator it = my_cin.begin(); it != my_cin.end(); it++)
{
if (isdigit(*it))
{
postfix_notion.push_back(*it);
}
else
{
if (*it == '(' || *it == '(')
{
_operator.push(*it);
}
else if (*it == ')' || *it == ')')
{
while ((_operator.top() != '(') &&( _operator.top() != '('))
{
postfix_notion.push_back(_operator.top());
_operator.pop();
}
_operator.pop();
}
else if (*it == '*' || *it == '/' || *it == '+' || *it == '-')
{
if (_operator.empty() || priority(*it, _operator.top()))
{
_operator.push(*it);
}
else
{
while (!_operator.empty()&&!priority(*it, _operator.top()))
{
postfix_notion.push_back(_operator.top());
_operator.pop();
}
_operator.push(*it);
}
}
else
{
cout << "错误字符,重新输入" << endl;
return postfix_notion;
}
}
}
if (!_operator.empty())
{
while (!_operator.empty())
{
postfix_notion.push_back(_operator.top());
_operator.pop();
}
}
return postfix_notion;
}
int Postfix_expression_calculator(std::vector<char>expression)
{
std::stack<int>_stack;
int num = 0;
for (std::vector<char>::iterator it = expression.begin(); it != expression.end(); it++)
{
if (isdigit(*it))
{
_stack.push(*it-'0');
}
else
{
int test;
int _2 = _stack.top();
_stack.pop();
int _1 = _stack.top();
_stack.pop();
if (*it == '+')
test= _1 + _2;
else if (*it == '-')
test= _1 - _2;
else if (*it == '*')
test= _1 * _2;
else
test= _1 / _2;
_stack.push(test);
}
}
return _stack.top();
}
中缀表达式转后缀表达式+后缀表达式运算的计算器代码(简易版,bug很多)
最新推荐文章于 2024-11-15 17:20:09 发布