parsing math expression in c++(在 C++ 中解析数学表达式)
问题描述
我有一个关于解析树的问题:
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++ 中解析数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中解析数学表达式


- 如何对自定义类的向量使用std::find()? 2022-11-07
- 从python回调到c++的选项 2022-11-16
- Stroustrup 的 Simple_window.h 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01