Qt QList not working as expected

I am building a QList<QList<double>> * the following way, to be returned in function randomPoint():

QList<QList<double>> *solverMethod::randomPoint(double* bottom_, double* top_, int items_)
{  
    QList<QList<double>> *lstPt_ = new QList<QList<double>>;

         for(int i=0;i<items_;i++)
        {   
            QList<double>  pt_;
            lstPt_->append(pt_);
            for(int j=0;j<m_ndim;j++)
            {
                pt_.append(TRandom::rand(bottom_[j],top_[j]));
            }
         }
        return lstPt_;
 }

But with a stopping point after for loop, I notice that pt_ is filled in properly (m_ndim elements), whereas lstPt is made of item_ empty QList<double>. What is happening?

Answers


lstPt_->append(pt_);

This puts a copy of pt_ in the outer list. You then populate the local pt_, leaving the copy empty. You should move this line after the loop that fills pt_. Specifically:

QList<double>  pt_;
for(int j=0;j<m_ndim;j++)
{
    pt_.append(TRandom::rand(bottom_[j],top_[j]));
}
lstPt_->append(pt_);

Try this:

QList<double>  pt_;
for(int j=0;j<m_ndim;j++)
{
    pt_.append(TRandom::rand(bottom_[j],top_[j]));
}
lstPt_->append(pt_);

When you do this:

lstPt_->append(pt_);

a copy of pt_ is added to lstPt_ (the copy constructor of QList will be invoked). So if pt_ is empty when you add it to lstPt_, then an empty list will be added. An alternative would be to use:

QList< QList<double>* > lstPt_;
...
QList<double>*  pt_ = new QList<double>;
lstPt_->append(pt_);
for(...)
{
    ...
}

In this case you don't have this problem, but you have to clean up (delete) every single instance of pt_ you create.

Gerald


Need Your Help

json not received in jsp through jquery-ajax

jquery ajax json jsp servlets

i am sending 2 data to the servlet through ajax from jsp and the servlet just get those data, then convert to json obj and return that json. now the jsp get that json to show those 2 data. ajax is

JVM as Maven Dependency

java maven vagrant maven-assembly-plugin

Is it possible to have a JVM as a Maven Dependency in a project?