c++ - 否定后缀不正确且可交流

标签 c++ stack postfix-notation

所以我正在使用堆栈 评估Postfix 表达式。表达式 10 6 - 读作 10 - 6 中缀,应该等于 4。但它不是,它等于 -4。更糟糕的是,即使我尝试反转代码,它仍然等于 -4。我不确定这是否是我的堆栈、函数调用或 C++ 的某些怪癖有问题。但是,如果我将堆栈中的 1 个弹出值存储在一个变量中,然后计算等式,它就可以正常工作。

相关代码: 栈类

template <class Item>
class stack {
private:
    struct node {
        Item item;
        node* next;
        node(Item x, node* t) {
            item = x;
            next = t;
        }
    };
    typedef node* link;
    link head;

public:
    stack(int) { head = 0; }
    int empty() const { return head == 0; }
    void push(Item x) { head = new node(x, head); }
    Item pop() {
        Item v = head->item;
        link t = head->next;
        delete head;
        head = t;
        return v;
    }
};

Evalutating the negative operation

    else if (argv[i][0] == '-') {
    stck.push(((-1) * stck.pop()) + stck.pop()); // A-B = -B+A
    // stck.push(stck.pop()+((-1)*stck.pop())); //A-B = -B+A
} // Both equations equal the same thing (Note I dont use both at the same
  // time)

这行得通

int n = (stck.pop());
stck.push(-1*n+stck.pop()); //A-B = -B+A

最佳答案

是的,这是一个 "quirk of C++" : 评估此特定表达式中的参数的顺序未定义。奇怪的是你两次得到相同的结果,但你通常不应该假设这些 pops 是从左到右计算的!

来自链接文章的“隐藏依赖项”部分:

x = f() + g() + h();

Is there any doubt about what will happen? At first sight it appears as though nothing could go wrong here. The 3 functions will be called in indefinite order, the sum of their return values will be calculated and an assignment will be performed. But, what if all 3 functions would access a shared static or global variable that they read and modify? We do not know in which order the 3 functions will be invoked and for that reason we would not know in which order read and write access to the shared data would be performed. Again, another sequence point challenge.

解决方案:使用临时变量。

关于c++ - 否定后缀不正确且可交流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26021622/

相关文章:

c++ - qt写入结束文件

c++ - 段错误将引用作为函数参数传递

c++ - 调试后缀计算器

java - Postfix 评估器未返回正确的结果

c++ - 如何重载逗号运算符以将值分配给数组

c++ - 我不明白 <Inside The C++ Object Model> 中 'Argument Initialization' 中的内容

c - 即使在函数调用完成后也可以访问堆栈上的内存位置

java - 如何在Java中用单词替换字符

c++ - 将联盟重新解释为其他联盟

Python - 连接或堆叠两个以上不同形状的数组