是否有一个标准的C ++工具来解析算术表达式?

时间:2014-05-28 15:48:49

标签: 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
       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;

}

你可以忽略我开始写的那些垃圾。我只是放弃了。是时候看看有人已经做了我想做的事。

我拥有的运算符按优先顺序排列为^*/+-。等式中的函数可能是xsin(x)cos(x)e^xlog(x)(尽管我希望以后能够添加更多) 。做我想做的事情有没有标准的机制?

2 个答案:

答案 0 :(得分:5)

你最想要做的是将表达式分解为表达式树 - 以这种形式处理它会容易得多。

要做到这一点,首先你需要某种解析器,它会将表达式分解为令牌。然后,您可以使用反向波兰表示法转换算法来构建表达式树。 Wikipedia page有很多相关的信息。

在您的示例中,表达式树如下所示:

x*sin(x)+x^2

     +
   /   \
  *     ^
 / \   / \
x sin x   2
   |
   x

使用此树,您可以以任何方式轻松处理整个表达式。

答案 1 :(得分:2)

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