C++ 标准算法将一个表达式分成由最低优先级运算符分隔的 2 个表达式?

标签 c++

我正在制作的类(class)需要一个函数,我在里面的评论中对此进行了详细说明:

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;
    std::string::const_iterator it(eq.begin()), offend(eq.end());
    while (it != offend)
    {
        /* ... */
    }

    return eqGood;

}

它使用一个枚举器 enum eqOps { ADDITION, SUBTRACTION, MULTIPLICATION, DIVISION, COMPOSITION, NONE }; 在命名空间 CalcWizConsts 中定义。表达式中可以找到的函数有sin(...), cos(...), e^(...)日志(...)。对于运算符 COMPOSITION 单词的示例,函数 log(x^2) 将被划分为 eq1=log(x)eq2=x^ 2oper=COMPOSITION

我原本打算尝试编写我自己的程序,但我已经屈服并决定看看这种类型的事情是否是一个已解决的问题,我可以通过某种通用的库算法获得其解决方案,您可能了解。你能指引我正确的方向吗?

最佳答案

尝试查看 Recursive Descent Parser 以获得灵感,您需要为其提供标识符标记,例如)x、sin、cos、e^、log、运算符,例如)+、-、*、/来自读取的词法分析函数一个字符串。 COMPOSITION运算符的解释似乎很奇怪,( ... ) 的内容看起来像是组合成一个表达式,所以函数对一元表达式进行操作。

关于C++ 标准算法将一个表达式分成由最低优先级运算符分隔的 2 个表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23834890/

相关文章:

c++ - 返回指针的开头?

c++ - 跨 C++ 翻译单元的初始化

c++ - swscanf_s 在读入 wchar_t 数组时导致错误

c++ - 从 BST 中删除一个元素(指针错误)

c++ - 在 OpenCV 中绘制梯度 vector 场

c++ - 模板之间的隐式转换

c++ - auto 声明的变量有时是通过引用?

c++ - Arduino - 如何从serial.read()提供结构?

c++ - C++ 中的 std::set 删除器不起作用

c++ - 为什么 stringstreams rdbuf() 和 str() 给我不同的输出?