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

2023-02-12C/C++开发问题
5

本文介绍了在 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++ 中解析数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6