我正在尝试实现postfix-expression评估,这是我的代码:
#include<iostream>
#include<string.h>
using namespace std;
template < class T > class Stack {
private:
T * s;
int n;
public:
Stack(int maxn) {
s = new T[maxn];
n = 0;
}
int empth() const {
return n == 0;
}
void push(T item) {
s[n++] = item;
}
int pop() {
return s[--n];
}
};
int main()
{
string a = "598+46**7+*";
int n = a.length();
Stack < int >save(n);
for (int i = 0; i < n; i++) {
if (a[i] == "+")
save.push(save.pop() + save.pop());
if (a[i] == "*")
save.push(save.pop() * save.pop());
if ((a[i] >= '0') && (a[i] <= '9'))
save.push(0);
while ((a[i] >= '0') && (a[i] <= '9'))
save.push(10 * save.pop() + (a[i++] - '0'));
}
cout << save.pop() << endl;
return 0;
}
但我收到编译错误(我在linux(ubuntu 11.10)中实现它):
postfix.cpp:35:13: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
postfix.cpp:37:10: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
我该如何解决这个问题?
答案 0 :(得分:5)
for(int i=0;i<n;i++){
if(a[i]=="+")
save.push(save.pop()+save.pop());
if(a[i]=="*")
比较字符时需要使用单引号
for(int i=0;i<n;i++){
if(a[i]=='+')
save.push(save.pop()+save.pop());
if(a[i]=='*')
答案 1 :(得分:0)
这是评估后缀表达式的link。