问题描述
我有一个关于解析树的问题:
I have a question about Parsing Trees:
我有一个字符串(数学表达式 estring),例如:(a+b)*c-(d-e)*f/g
.我必须在树中解析该表达式:
I have a string (math expresion estring), for example: (a+b)*c-(d-e)*f/g
. I have to parse that expression in a Tree:
class Exp{};
class Term: public Exp{
int n_;
}
class Node: Public Exp{
Exp* loperator_;
Exp* roperator_;
char operation; // +, -, *, /
}
我可以使用什么算法来构建表示上述表达式字符串的树?
What algorithm can I use to build a tree which represents the expresion string above?
推荐答案
使用 Shunting-yard 算法.维基百科的描述相当全面,我希望它足够了.
Use the Shunting-yard algorithm. The wikipedia description is quite comprehensive, I hope it will suffice.
您也可以尝试编写形式化语法,例如解析表达式语法,并使用工具生成解析器.这个关于 PEG 的站点列出了 3 个用于 PEG 解析的 C/C++ 库.
You can also try to write a formal grammar, for example a parsing-expression grammar, and use a tool to generate a parser. This site about PEGs lists 3 C/C++ libraries for PEG parsing.
这篇关于在 C++ 中解析数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!