缀以Postfix和一元/二元运算符 [英] Infix to Postfix and unary/binary operators

查看:236
本文介绍了缀以Postfix和一元/二元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,中缀表达式转换为表达式树在内存中。这只是正常。这里有一个小的麻烦。我刚接工作,如何正确的一元运算符(右关联的)涉及

I have a piece of code that converts an infix expression to an expression tree in memory. This works just fine. There's just one small trouble. I just connect work out how to involve the unary operators correctly (the right associative ones).

通过以​​下缀表达式:

With the following infix expression :

+1 + +2 - -3 - -4

我期望的RPN:

1+2++3-4--

然而,没有一个线上缀后转换器,我可以找到我期望的方式处理这个问题的例子。 ?有没有人有处理权的关联经营者,特别是二进制的,可以被误认为是一元的人解释清楚。

Yet, none of the online infix-post converters I can find handle this example in the way I would expect. Does anyone have a clear explanation of handling right associative operators, specifically the binary ones that can be mistaken for the unary ones?

编辑/澄清:
我会想知道如何从缀翻译为后缀中处理元运算符。即:识别相同 - 例如字符作为是一元的,而不是二元运算符因而不同的优先级。我想用一个状态机也许两种状态,但...?

Edit/Clarification: I would like to know how to deal with the unary operators during the translation from infix to postfix. Ie: recognizing the same '-' character for example as being unary instead of binary operator and thus a different precedence. I would think of using a state machine perhaps with two states but ...?

推荐答案

那么,你需要确定一个鉴于操作员在的解析<​​/ em>的舞台二元/一元。一旦你这样做,当你创建了RPN,您可以标记运营商服用2个或1个参数

Well, you need to determine if a given operator is binary/unary during the parsing stage. Once you do that, when you create the RPN, you can tag the operators as taking 2 or 1 arguments.

您可以尝试使用的Shunting堆场算法做解析(RPN和创造在同一时间),这是设计的一元运算符太工作。

You could try using the Shunting Yard algorithm to do the parsing (and creation of RPN at the same time), which was designed to work with unary operators too.

在任何情况下,如果所有你关心的是一元的+或 - ,你可以只插入带括号0,当你看到一个+或 - 出现意外

In any case, if all you care about is unary + or -, you could just insert a 0 with brackets when you see a + or - that appears 'unexpectedly'.

例如

+1 +2 + - -3 - -4

您应该能够通过它来作一通,并转换为

You should be able to make a pass through it and convert to

(0 + 1)+(0 + 2) - (0-3) - (0-4)

现在你不吨需要担心一元+或 - 而且或许可以忘记与他们采取的参数个数标记运营商

Now you don't need to worry about the unary + or - and can probably forget about tagging the operators with the number of arguments they take.

这篇关于缀以Postfix和一元/二元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆