在C ++中解析数学表达式 [英] parsing math expression in c++
本文介绍了在C ++中解析数学表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对解析树有疑问:
我有一个字符串(数学表达式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 ++中解析数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文