C++ 是否有标准的C++;解析算术表达式的工具?
我要做的是在函数内部的注释块中描述的:C++ 是否有标准的C++;解析算术表达式的工具?,c++,C++,我要做的是在函数内部的注释块中描述的: 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
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) : '\0');
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
使用此树,您可以轻松地以任何方式处理整个表达式。您要查找的是一个可以将字符串转换为表示表达式的数据结构的树,并考虑运算符优先级。解析是一个广泛的话题,你需要做一些阅读,但是库是一个在C++中编写解析器的体面的方法,并且还提供一些有用的背景(虽然它不是C++特有的)。分区的期望输出:代码< > x ^ 2 +x+ 1 < /> >此外,我们是否要假设输入在语法上已经有效?(例如,没有什么比
x^^^5++2
)我正在检查语法的有效性,对于一个非常无意义的问题,x^2+x+1的分区将是eq1=x^2和eq2=x+1-1title@GigaWatt事实上,这是可以毫不含糊地解决的。创建数学表达式编译器时,定义已关联的运算符的关联方向非常有用。例如,为了算法的缘故,你可以假设a+b+c=(a+b)+c,是什么让你明确地“划分”成(a+b)和c.@user3681052,我已经编辑了你的标题。您可以随意更改它,但这应该能让您很好地了解标题应该是什么样子。