头文件
// expressions.h: interface for the expression class.
//
//
#if !defined(AFX_EXPRESSION_H__5CBE655C_7DC8_432D_9777_4F8B16458183__INCLUDED_)
#define AFX_EXPRESSION_H__5CBE655C_7DC8_432D_9777_4F8B16458183__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <string>
#include <map>
class expressions
{
public:
expressions();
virtual ~expressions();
std::string postorder(std::string );//后缀表达式
private:
int priority(char op1,char op2);//优先级 op1 > op2 1 op1==op2 0 op1 < op2 -1
std::map<char,int> mOp;
};
#endif // !defined(AFX_EXPRESSION_H__5CBE655C_7DC8_432D_9777_4F8B16458183__INCLUDED_)
源文件
// expressions.cpp: implementation of the expressions class.
//
//
#include "stdafx.h"
#include "expressions.h"
#include <utility>
#include <stack>
#include <iostream>
//
// Construction/Destruction
//
using namespace std;
typedef struct _op{
public:
char opstr;
int level;
}op;
static op oparr[] = {
{' ',0},
{'+',1},
{'-',1},
{'*',2},
{'/',2}
};
expressions::expressions()
{
char ckey;
int nvalue;
for(int i=0;i<sizeof(oparr)/sizeof(op);++i)
{
ckey = oparr[i].opstr;
nvalue = oparr[i].level;
mOp.insert(std::make_pair<char,int>(ckey,nvalue));
}
}
expressions::~expressions()
{
}
std::string expressions::postorder(std::string expstr)
{
stack<char> ops;
string sret;
string svalue;
string ssep = " \n()\r+-*/";
string ssp = " \n\r";
string sop = "+-*/";
for(int i=0;i<expstr.size();++i)
{
char& ch = expstr[i];
if(ssep.find(ch) == -1)
{
//元素
svalue += ch;
}
else
{
//分隔符
sret += svalue;
svalue = "";
if(ssp.find(ch) != -1)
{
//空白符
continue;
}
sret += ' ';
}
if(ch == '(')
{
ops.push(ch);
}
else if(ch == ')')
{
while(ops.size() > 0)
{
char ctop = ops.empty() ? ' ' : ops.top();
if(ctop == '(')
{
ops.pop();
break;
}
else
{
sret += ctop;
sret += ' ';
ops.pop();
}
}
}
else if(sop.find(ch) != -1)
{
//操作符
//比较当前操作符和栈顶操作符优先级
char ctop = ops.empty() ? ' ' : ops.top();
int ret = priority(ch, ctop);
if(ret > 0 || ch == '(')
{
ops.push(ch);
}
else
{
while(ops.size() > 0)
{
char ctop = ops.empty() ? ' ' : ops.top();
int ret = priority(ch, ctop);
if(ret > 0 || ctop == '(')
{
ops.push(ch);
break;
}
else
{
sret += ctop;
sret += ' ';
ops.pop();
}
}
if(ops.size() == 0)
{
ops.push(ch);
}
}
}
}
sret += svalue;
sret += ' ';
//所有操作符出栈
while(ops.size() > 0)
{
sret += ops.top();
sret += ' ';
ops.pop();
}
return sret;
}
int expressions::priority(char op1,char op2)
{
int level1 = 0,level2 = 0;
level1 = mOp[op1];
level2 = mOp[op2];
if(level1 > level2)
{
return 1;
}
else if(level1 < level2)
{
return -1;
}
return 0;
}
测试
// expessiontest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "expressions.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
expressions exp;
cout<<exp.postorder(" a + b - c* 10 / 2+34");
return 0;
}
转载于:https://blog.51cto.com/weiwang079x/1358964