有没有标准的c++工具来解析算术表达式?
Is there a standard C++ tool to parse arithmetic expressions?
我要做的是在函数内的注释块中描述:
bool CalculusWizard::partitionEquation(const std::string & eq, std::string & eq1,
std::string & eq2, CalcWizConsts::eqOps & oper)
{
/* Given an equation eq, partion eq into
eq = eq1 oper eq2
where oper is the operator with the lowest precedence,
e.g. eq = "x*sin(x)+x^2" --> eq1 = "x*sin(x)", oper = ADDITION, eq2 = "x^2".
If there is no operator, e.g. eq = "x", then oper = NONE.
The error checking is done in this function. If there is a syntactical error
in eq, then return false.
*/
bool eqGood = true;
eq1.clear();
eq2.clear();
oper = CalcWizConsts::NONE;
int netParans = 0;
std::string::const_iterator it(eq.begin()), offend(eq.end());
while (it != offend)
{
char thisChar(*it);
char nextChar(((it+1) != offend) ? *(it+1) : ' ');
if (thisChar == '(')
{
if ()
++netParans;
}
else if (thisChar == ')')
{
if (isOp(nextChar))
{
}
--netParans;
}
else if (CalcWizConsts::digMap.count(thisChar) == 1)
{
}
}
if (netParans != 0)
eqGood = false;
return eqGood;
}
你可以忽略我已经开始写的垃圾。我几乎要放弃了。是时候看看是否有人已经做过我想做的事了。
我拥有的操作符,按优先级排序是^
, *
, /
, +
和-
。可能在方程中的函数是x
, sin(x)
, cos(x)
, e^x
和log(x)
(虽然我希望以后能够添加更多)。有什么标准的机制来做我想做的吗?
您最可能想做的是将表达式分解成表达式树-在这种形式下处理起来容易得多。
要做到这一点,首先需要某种解析器,它将表达式分解为令牌。然后,您可以使用反向波兰符号转换算法来构建表达式树。维基百科页面有很多相关信息。
在您的示例中,表达式树看起来如下:
x*sin(x)+x^2
+
/
* ^
/ /
x sin x 2
|
x
有了这个树,你可以很容易地以任何你想要的方式处理整个表达式。
您正在寻找的是一个解析器,它可以将字符串转换为表示表达式的数据结构,并考虑运算符优先级。解析是一个广泛的话题,你需要做一些阅读,但是Boost Spirit库是用c++编写解析器的一种体面的方式,这个SO问题也提供了一些有用的背景知识(尽管它不是特定于c++)。
相关文章:
- (C++)分析树以计算返回错误值的简单算术表达式
- 使用CMake检测支持的C++标准
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- 使用 lambda 表达式的 Raspbian G++ 8.3.0 导致 ']' 之前的预期主表达式 - 即使标准设置为 c++14
- 标准库中的任何正则表达式语法是否支持 (?(定义)用于子模式参考?
- 使用C++11标准的哪些规则来确定({..})中表达式的类型
- C++ 增强正则表达式与标准库正则表达式匹配结果
- C 标准中的哪个段落验证了以下示例中使用的表达式`sizeof(s :: m 42)`
- 如何对标准::正则表达式进行哈希处理
- 在c++中,全局作用域中只允许"表达式"初始化全局对象.我在哪里可以在标准中找到这个
- C++11标准中的核心常量表达式是什么
- 巨大的程序大小C++与标准::正则表达式
- 为什么C++标准使正则表达式算法成为免费函数
- 标准::max_element 上二进制表达式的操作数无效
- 保存/序列化提升或标准正则表达式
- 为什么赋值表达式的标准C++语法看起来如此怪异
- Mex运行时错误:意外的标准表达式
- 有没有标准的c++工具来解析算术表达式?
- c++标准算法,用最低优先级的运算符分隔一个表达式为两个表达式
- 标准::C++正则表达式中有最大组限制吗?