在 C++ 中解析数学表达式

编程入门 行业动态 更新时间:2024-10-18 16:46:13
本文介绍了在 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++ 中解析数学表达式

本文发布于:2023-11-10 16:14:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575857.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   数学

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!