有没有标准的c++工具来解析算术表达式?

Is there a standard C++ tool to parse arithmetic expressions?

本文关键字:表达式 标准 c++ 工具 有没有      更新时间:2023-10-16

我要做的是在函数内的注释块中描述:

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^xlog(x)(虽然我希望以后能够添加更多)。有什么标准的机制来做我想做的吗?

您最可能想做的是将表达式分解成表达式树-在这种形式下处理起来容易得多。

要做到这一点,首先需要某种解析器,它将表达式分解为令牌。然后,您可以使用反向波兰符号转换算法来构建表达式树。维基百科页面有很多相关信息。

在您的示例中,表达式树看起来如下:

x*sin(x)+x^2
     +
   /   
  *     ^
 /    / 
x sin x   2
   |
   x

有了这个树,你可以很容易地以任何你想要的方式处理整个表达式。

您正在寻找的是一个解析器,它可以将字符串转换为表示表达式的数据结构,并考虑运算符优先级。解析是一个广泛的话题,你需要做一些阅读,但是Boost Spirit库是用c++编写解析器的一种体面的方式,这个SO问题也提供了一些有用的背景知识(尽管它不是特定于c++)。