我正在用 C++ 做一个解析函数,它接受一个字符串和一个 double 作为参数并返回字符串的“值”。
代码如下:
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;
}
但这当然行不通。有任何想法吗 ? (类(class)等)
谢谢。
最佳答案
您可以为此使用函数指针。如果你也想要一个函数指针作为参数,我不太明白,但你可以这样做:
typedef double (*handler) (double);
double add(handler x, handler y);
double sub(handler x, handler y);
double func1(double n);
double func2(double n);
int main()
{
double (*funcPtr[256]) (double);
funcPtr['+'] = func1;
funcPtr['-'] = func2;
double answer = funcPtr['+'](2));
}
double func1(double n)
{
return n;
}
double func2(double n)
{
return n;
}
double add(handler x, handler y)
{
return x(2) + y(2);
}
double sub(handler x, handler y)
{
return x(4) - y(2);
}
如果这不是您要查找的内容,但类似于下面的代码,请告诉我,我将编辑我的答案:
funcPtr[toParse[i]](2, 2); // toParse[i] is '+' it will then call add(2,2)
256 大小的 funcPtr
数组是关于 sizeof(char)
的。您应该确保 index
是数组中的实际值,否则您将越界访问。
关于c++ - 增加两个功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24662218/