How to use QVector with double
-
Hi! It might seem like a silly question but I am unable to initialize QVector. Here is what is happening:
QVector<double> vec(10); // Error: Expected a type specifier
I am initializing this in my .h file and I am using
#include <QVector>
. Isn't this how we are supposed to initialize QVector? -
Isn't this how we are supposed to initialize QVector?
Yes and no. This is how you'd initialize a local variable in a function.
If it's a class member you can initialize it like thisQVector<double> vec = QVector<double>(10);
or with braces if it's not too much to type:
QVector<double> vec {0,0,0,0,0,0,0,0,0,0};
-
@Chris-Kawa Thank you! I knew it had to be something simple like this but was unable to find it on the internet.
-
To be honest initialization in C++ is a bit of a mess and it's easy to get it wrong.
There's a nice talk about this and related stuff from few years back: "The Nightmare of Initialization in C++". -
@Chris-Kawa said in How to use QVector with double:
or with braces if it's not too much to type:
QVector<double> vec {0,0,0,0,0,0,0,0,0,0};
or
QVector<double> vd(10,0.0);
if its too much to type , but the same value
-
@Chris-Kawa Yeah, sometimes it is very frustrating with simple things, especially since I am new to C++. Tanks for the video link, I will watch it soon in my spare time :)
-
@J-Hilk said:
QVector<double> vd(10,0.0);
if its too much to type , but the same valueThat's not gonna compile as a class member declaration. As a local variable it's the same as
QVector<double> vd(10)
as0.0
is the default value for double. -
fair enough 😉
but,
...
as member initialization, you could do:QVector<double> vec2{QVector<double>(10)}; QVector<double> vec{QVector<double>(10,0.0)};
you're right, there are way to many ways to initialize stuff in c++ !