c++exprtk

Get vector from exprTk as output


I can't seem to get a vector output from exprTk. I figure it should be relatively simple but in the manual I can only find how to input a vector and not how to output one.

What I currently have is the following:

typedef double T; // numeric type (float, double, mpfr etc...)
typedef exprtk::symbol_table<T> symbol_table_t;
typedef exprtk::expression<T>     expression_t;
typedef exprtk::parser<T>             parser_t;

std::string expression_string = "var z[2] := { x, y };";

T x = T(5.3);
T y = T(2.3);
std::vector<T> z;

symbol_table_t symbol_table;
symbol_table.add_variable("x", x);
symbol_table.add_variable("y", y);
symbol_table.add_vector("z", z);

expression_t expression;
expression.register_symbol_table(symbol_table);

//Check if expression is valid
parser_t parser;
if (!parser.compile(expression_string, expression))
{
    printf("Compilation error...\n");
    return;
}

T result = expression.value();
std::cout << result << std::endl;     \\returns: 5.3 as expected the first element of vector z.
std::cout << z[0] << std::endl;       \\Crashes the program 

What I want as output is just the vector z. How do I do this, or what am I doing wrong?


Solution

  • I've found a method that does work, but hopefully there is a simpler 'one-line' method

    std::string expression_string = "var w[2] := { x, y }; z := w";
    

    This creates an expression local vector w ([SECTION 13 - VARIABLE, VECTOR & STRING DEFINITION]), and then assigns the value to z

    As @NathanOliver mentioned, std::vector<T> z(2); is also needed


    "var z[2] := { x, y };" doesn't work as it is an illegal redefinition of the z variable, due to the use of the var statement.

    Note that "z := {x, y}" will also not work as this does not appear to be a valid assignment expression for a vector


    Output (with debug enabled):

    prev[var] --> curr[var]
    prev[var] --> curr[w]
    prev[2] --> curr[]]
    prev[x] --> curr[,]
    prev[y] --> curr[}]
    parse_define_vector_statement() - INFO - Added new local vector: w[2]
    activate_side_effect() - caller: parse_define_vector_statement()
    parse_corpus(00) Subexpr: var w[2] := { x, y };
    parse_corpus(00) - Side effect present: true
    -------------------------------------------------
    prev[z] --> curr[:=]
    prev[:=] --> curr[w]
    prev[w] --> curr[]
    activate_side_effect() - caller: lodge_assignment()
    parse_corpus(01) Subexpr: z := w
    parse_corpus(01) - Side effect present: true
    -------------------------------------------------
    5.3
    5.3