PDA

View Full Version : QList += operator



alrawab
12th January 2013, 07:29
i got error when try :



QList<double> zz;
double r=.05;
for (int k = 0; k < 3; ++k)
{
zz[0] +=r;

}


how to solve this
thanks

Lykurg
12th January 2013, 07:45
In general it would be helpfull if you would actually paste the error message!

As far as I can see, you have to fill the list first. [] can only be used if that index allready exists.

alrawab
12th January 2013, 08:46
you have to fill the list first. []
yes i did that by :


zz<<0.0<<0.0<<0.0<<0.0

but that is idiot

wysota
12th January 2013, 12:34
What (who?) is idiot?

alrawab
12th January 2013, 13:01
There is no need to inquire not my nature abuse literature with one .
I meant the Behavior of the QList
that is all

wysota
12th January 2013, 13:06
What behaviour of QList? That you can't operate on items you don't have? Every list works this way. It's a list with finite number of elements.

alrawab
12th January 2013, 13:13
but in c# for example you don't obligate to initialize initial values :


doble zz=3;
double[] foo = new double[4];
for (int k = 0; k <10; ++k)
{
foo[0] += zz;


}

this is similar to QList and works fluently without any initialization

wysota
12th January 2013, 13:40
No, you are wrong. This is the initialization of the array:

double[] foo = new double[4];
You explicitly set the array size to four elements filled with possibly random data.

The equivalent for Qt (with the difference that each cell is initialized to 0.0) is:

QVector<double> foo(4);

alrawab
12th January 2013, 14:23
:) yes but this not applicable For QList as i know ?
is there any replacement for zz<<0.0<<0.0<<0.0<<0.0;
it's looks ugly

amleto
12th January 2013, 16:09
use QVector

wysota
12th January 2013, 16:24
:) yes but this not applicable For QList as i know ?
It's a list. Initializing it like I did with a vector is slow and unnecessary.


is there any replacement for zz<<0.0<<0.0<<0.0<<0.0;
e.g.

for(int i=0;i<4;++i) zz.append(0);

By the way, if you know your array of doubles is going to be always of size 4, use a regular C array instead.


double zz[4];

ChrisW67
13th January 2013, 22:25
If the object is to always have a fixed number of elements then you have better choices than QList as others have pointed out. If your QList must start with a certain number of elements but may grow, and you really find the simple initialisation loop so distasteful, then I guess you can use QVector to initialise your QList:


QList<double> stuff = QList<double>::fromVector(QVector<double>(4, 0.0));

I don't think this is an improvement over the other options. Ultimately expecting C++ and Qt to behave like C# and its library is like tilting at windmills (http://www.wikipedia.org/wiki/Tilting_at_windmills).

wysota
14th January 2013, 00:11
With C++11 and Qt 5 one can also use initializer lists.


QList<double> xxx = { 0.0, 0.0, 0.0, 0.0 }; // with C++11 enabled