我正在制作的类(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^ 2
与 oper=COMPOSITION
。
我原本打算尝试编写我自己的程序,但我已经屈服并决定看看这种类型的事情是否是一个已解决的问题,我可以通过某种通用的库算法获得其解决方案,您可能了解。你能指引我正确的方向吗?
最佳答案
尝试查看 Recursive Descent Parser 以获得灵感,您需要为其提供标识符标记,例如)x、sin、cos、e^、log、运算符,例如)+、-、*、/来自读取的词法分析函数一个字符串。 COMPOSITION运算符的解释似乎很奇怪,( ... ) 的内容看起来像是组合成一个表达式,所以函数对一元表达式进行操作。
关于C++ 标准算法将一个表达式分成由最低优先级运算符分隔的 2 个表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23834890/