C++逻辑条件的中缀到前缀转换
我想计算 C++ 中的一个表达式。为了评估它,我希望将表达式转换为前缀格式。
这是一个示例
wstring expression = "Feature1 And Feature2";
以下是可能的方法。
expression = "Feature1 And (Feature2 Or Feature3)";
expression = "Not Feature1 Or Feature3";
这里And、Or、Not是保留字和括号(“(”, )) 用于范围
Not 具有更高的优先级
And 设置为 Not 的下一个优先级
Or 设置为 And
的 下一个优先级空格用于分隔符。表达式没有其他元素,例如TAB、NEWLINE
我不需要需要算术表达式。我可以进行评估,但有人可以帮助我将字符串转换为前缀表示法吗?
I want to evaluate one expression in C++. To evaluate it, I want the expression to be converted to prefix format.
Here is an example
wstring expression = "Feature1 And Feature2";
Here are possible ways.
expression = "Feature1 And (Feature2 Or Feature3)";
expression = "Not Feature1 Or Feature3";
Here And, Or, Not are reserved words and parentheses ("(", )) are used for scope
Not has higher precedence
And is set next precedence to Not
Or is set to next precedence to And
WHITE SPACE used for delimiter. Expression has no other elements like TAB, NEWLINE
I don't need arithmetic expressions. I can do the evaluation but can somebody help me to convert the strings to prefix notation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要预先构建语法。那么为什么要手动进行所有解析呢?
相反,请使用解析器构建器库,例如 Boost-Spirit。或者 lex/yacc 或 flex/bison。
然后使用解析器构建器生成的 AST 以您认为合适的任何方式输出数据。例如前缀或后缀的中缀,...等。
You will need to construct the grammar up front. So why do all the parsing by hand.
Instead use a parser builder library like Boost-Spirit. Or lex/yacc or flex/bison.
Then use the AST generated by the parser builder to output the data in any way you see fit. Such as infix to prefix or postfix, ...etc.
我猜你的目的是评估状况。因此你不需要一个成熟的解析器。
首先,您不需要在这里使用字符串。
1. 将“Feature 1”转换为 Id(代表特征的整数)
因此,语句
"Feature1 And (Feature2 Or Feature3)";
表示(1 & ( 2 | 3)
从这里开始...您可以使用标准中缀进行前缀转换并评估前缀表示法。
这是将中缀转换为前缀的算法
http://www.c4swimmers.esmartguy.com/in2pre.htm
http://www.programmersheaven.com/2/Art_Expressions_p1
I guess your intention is to evaluate condition. hence you dont need a full fledged parser.
First of all you dont need to work with strings here.
1. Convert "Feature 1" to say an Id (An integer which represents a feature)
So, the statement
"Feature1 And (Feature2 Or Feature3)";
to say(1 & (2 | 3)
From here on...you can use the standard Infix to prefix conversion and evaluate th prefix notation.
Here is the algorithm to convert infix to prefix
http://www.c4swimmers.esmartguy.com/in2pre.htm
http://www.programmersheaven.com/2/Art_Expressions_p1
使用像 Lex/Yacc 对这样的解析器生成器。
Use a parser generator like the Lex/Yacc pair.