【发布时间】:2014-07-09 19:27:02
【问题描述】:
我在 C++ 中做一个解析函数,它接受一个字符串和一个双精度作为参数,并返回字符串的“值”。
代码如下:
double evaluate (char * toParse, int length, double x)
{
// Case 'x'
if ((toParse[0] == 'x') &&
(length == 1))
{
return x;
}
// Case value
char * endptr;
double num = strtod(toParse, &endptr);
if(endptr - toParse == length)
{
return num;
}
// Parsing
int nBrackets = 0;
for (int i = 0; i < length; i++)
{
if (toParse[i] == '(')
{
nBrackets++;
}
else if (toParse[i] == ')')
{
nBrackets--;
}
// Remove brackets.
double _x = (toParse[0] == '(' && toParse[i-1] == ')' ) ?
evaluate(&toParse[1], i-2, x) : evaluate(toParse, i, x);
double _y = (toParse[i+1] == '(' && toParse[length-1] == ')' ) ?
evaluate(&toParse[i+2], length - (i+1) - 2, x) : evaluate (&toParse[i+1] , length - (i+1), x);
// Supports +, -, * and /
if (nBrackets == 0 &&
toParse[i] == '+')
{
return _x + _y;
}
else if (nBrackets == 0 &&
toParse[i] == '-')
{
return _x - _y;
}
else if (nBrackets == 0 &&
toParse[i] == '*')
{
return _x * _y;
}
else if (nBrackets == 0 &&
toParse[i] == '/')
{
return _x / _y;
}
}
return 0.;
}
int main()
{
cout << evaluate("((4*x)+7)-x", 11, 5.) << endl;
// Outputs 22, which sounds correct.
return 0;
}
它远非完美无缺(运算符没有优先级,如果字符串包含太多括号等则不起作用),但我想删除双 x 参数,并直接处理函数。 (因为我想绘制函数,如果我不处理函数,我将不得不为 x 的每个值解析相同的字符串...)
有可能吗?我的意思是,做类似的事情:
double (double) operator+ (double f(double), double g(double))
{
double h (double x)
{
return f(x)+g(x);
}
return h;
}
但它当然不起作用。有任何想法吗 ? (类等)
谢谢。
【问题讨论】:
-
在 C++11 中使用字符串字面量调用该函数是非法的。
-
C 和 C++ 都允许将指针传递给其他函数。
-
您好,谢谢三位! @chris:我不能只使用 std::string 来遵守 C++11 吗?我不介意改变它!
-
@Jongware:你能解释一下吗?我实际上看不到应该将哪个指针传递给哪个函数:(
-
return [=](double x) {return f(x)+g(x);};可以是std::function之类的,但只有当一种类型是用户定义的类型时,才能重载运算符。