gpt4 book ai didi

c++ - ExprTk:当表达式的值改变时是否必须重新编译表达式

转载 作者:太空狗 更新时间:2023-10-29 20:21:34 27 4
gpt4 key购买 nike

我正在用 exprtk 创建一个表达式使用不断变化的变量。

每次更改变量值时,我是否必须使用更新的 exprtk::symbol_table 重置和重新编译 exprtk::expression

或者更新后的值是否直接由现有的编译表达式求值?

#include <iostream> 
#include <string>
#include "exprtk.hpp"

int main() {
std::string expression_string = "y := x + 1";

int x = 1;

exprtk::symbol_table<int> symbol_table;
symbol_table.add_variable("x", x);

exprtk::expression<int> expression;
expression.register_symbol_table(symbol_table);

exprtk::parser<int> parser;

if (!parser.compile(expression_string, expression))
{
std::cout << "Compilation error." << std::endl;
return 1;
}

expression.value(); // 1 + 1

x = 2;
// Do I have to create a new symbol_table, expression and parse again?

// Or does the expression evaluate the new value directly?
expression.value(); // 2 + 1?

return 0;
}

最佳答案

exprtk::symbol_table 引用的变量值发生变化时,

exprtk::expression 不必 重新编译。 expression.value() 可以立即使用。

According to the documentation (第 10 节 - 组件),符号表中引用的变量的实际值在表达式被计算之前才被解析。所以用解析器编译相同的表达式必须只发生一次。

std::string expression_string = "x * y + 3";
symbol_table.add_variable("x",x);
symbol_table.add_variable("y",y);

expression.register_symbol_table(symbol_table);

parser.compile(expression_string,expression);

x = 1.0;
y = 2.0;
expression.value(); // 1 * 2 + 3

x = 3.7;
expression.value(); // 3.7 * 2 + 3

y = -9.0;
expression.value(); // 3.7 * -9 + 3

// 'x * -9 + 3' for x in range of [0,100) in steps of 0.0001
for (x = 0.0; x < 100.0; x += 0.0001)
{
expression.value(); // x * -9 + 3
}

During the compilation process [..] the element will be embedded within the expression's AST. This allows for the original element to be modified independently of the expression instance [...] the variables are modified as they normally would in a program, and when the expression is evaluated the current values assigned to the variables will be used.

关于c++ - ExprTk:当表达式的值改变时是否必须重新编译表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43312247/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com