中缀表达式转后缀表达式+后缀表达式运算的计算器代码(简易版,bug很多)

#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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值