std::vector is not getting modified in a lambda function. But I don't get any error as well

152 Views Asked by At

This is my code:

HelloApplication::HelloApplication(const Wt::WEnvironment& env)
    : Wt::WApplication(env)
{
    setTitle("Data Interpolation");

    Wt::WText *InitialExplanation = root()->addWidget(std::make_unique<Wt::WText>());

    InitialExplanation->setText("Welcome! This is a page that will allow you to interpolate the value at a point in the domain of your dataset, using other points in your dataset.\n I used Lagrange Interpolation for this calculation.\n Created By Vashist Hegde");

    root()->addWidget(std::make_unique<Wt::WBreak>());

    std::vector<double> xi;
    std::vector<double> yi;
    std::vector<double> xMissing;
    double xM;
   
    auto addDataPoint = [this,xi,yi,lineEdit1,lineEdit2] () mutable{
        
    /// neither of the following push_backs is working.
    /// I get 2 empty vectors in the end.
        xi.push_back(std::move(std::stod(lineEdit1->text())));
        yi.push_back(std::move(std::stod(lineEdit2->text())));

        xi.push_back(3.5);
        yi.push_back(4.5);

    };

I don't get any errors but when I run the program, the vectors are just not getting populated. I get 0 sized vectors. Is this related to my general C++ usage or is it related to Wt (C++ Web toolkit)? If it is related to the general C++ usage, please help me as to what I'm doing wrong.

1

There are 1 best solutions below

3
Const On

Your lambda should capture the variable by ref which has to be to be modified, otherwise the changes will be done to the copy of the captured things. Additionally, you need to invoke lambda for get in action.

auto addDataPoint = [this,&xi,&yi,lineEdit1,lineEdit2] () mutable {        
            // ...... do something
    };

addDataPoint(); // call lambda

alternatively pass them as ref qualified arguments

auto addDataPoint = [this, lineEdit1,lineEdit2] 
    (auto& xi_para, auto &yi_para,) mutable {        
            // ...... do something
    };

addDataPoint(xi, yi); // call lambda with args
````