后缀表达式求值

postfix -expression evaluation

本文关键字:表达式 后缀      更新时间:2023-10-16

我试图实现后缀表达式求值,这是我的代码:

#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]

如何解决这个问题?

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]=='*')

这是计算后缀表达式的链接。