c++ - 后缀评估,为什么推送函数不更新堆栈变量的顶部?

标签 c++ stack postfix-notation

当给出输入“53+”时,它正在推送 5 并将 tos 从“-1”更新为 0 但是当第二次调用该函数时,它推送 3 但 tos 仍然是 0,而不是 1。请帮助.

#include<iostream>

using namespace std;

int push(int tos, int x);
int pop(int tos);

int st[50];
int tos=-1;

int main()
{
    char str[30];
    int r,k,v1,v2,i;

    cin>>str;
    for(i=0;str[i]!='\0';i++)
    {
        if(str[i]!='*'&&str[i]!='-'&&str[i]!='+'&&str[i]!='/')
        {
            k=str[i]-'0';
            push(tos,k);
        }
        else
        {
            if(tos==-1||tos==0) 
                cout<<"enter correct format";
            else
            {
                v1=pop(tos);
                v2=pop(tos);
                switch(str[i])
                {
                case '*': r=v1*v2;
                    push(tos,r);
                    break;
                case '+': r=v1+v2;
                    push(tos,r);
                    break;
                case '-': r=v1-v2;
                    push(tos,r);
                    break;
                case '/': r=v1/v2;
                    push(tos,r);
                    break;
                default: 
                    cout<<"invalid";
                }
            }
        }
    }
    r=pop(tos);
    cout<<endl<<r;
    return 0;
}
int push(int tos, int x)
{
    if (tos==50-1)
        cout<<"overflow"<<endl;
    else
    {
        tos++;
        st[tos]=x;
        cout<<endl<<"pushed"<<tos<<st[tos];
    }
}

int pop(int tos)
{ 
    int z;
    if(tos==-1)
        cout<<"underflow";
    else
    {
        z=st[tos];
        tos-=1;
    }
    return z;
}

当给出输入“53+”时,它压入 5 并将 tos 从“-1”更新为 0,但是当第二次调用该函数时,它压入 3 但 tos 仍然是 0,而不是 1。

最佳答案

你的 push()pop()函数接收 tos按值,所以他们对 tos 所做的任何更改不反射(reflect)在功能之外。

一种解决方案是通过 tos通过引用,例如

int push(int &tos, int x)
{
    // Any changes to tos are now reflected in the variable passed in.
    ...
}

关于c++ - 后缀评估,为什么推送函数不更新堆栈变量的顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57082970/

相关文章:

azure - Azure 是用什么堆栈/编程语言编写的?

java - Java 中的子上下文在堆栈中是单独的行吗?

java - 我试图理解我的作业,java Lisp算术表达式

c++ - std::async int 函数可以在任务完成之前退出吗?

c++ - 在 .cpp 文件中实现时访问私有(private)成员

c++ - 分配整数数组时如何防止发生SIGABRT?

objective-c - 后缀到中缀转换器 Objective C

java - 在遗传算法中,应该使用什么交叉方法来交叉 Postfix 表达式?

c++ - 预处理器定义在 Visual Studio 中有效,在 Qt-creator 中无效

c++ - 链接旧服务器 c++ 时出错