QVector construct with multiple object

73 Views Asked by At

I want to QVector start with several QSoundEffects (pratically). I try below code but not work.

QVector<QSoundEffect *> reelSounds(4,new QSoundEffect());

I also don't want to go to a long method like this

.h file

QVector<QSoundEffect *> reelSounds;

.cpp

reelSounds.resize(4);
QSoundEffect *sound0= new QSoundEffect();
QSoundEffect *sound1= new QSoundEffect();
QSoundEffect *sound2= new QSoundEffect();
QSoundEffect *sound3= new QSoundEffect();
reelSounds[0] = sound0;
reelSounds[1] = sound1;
reelSounds[2] = sound2;
reelSounds[3] = sound3;

or

QSoundEffect *sound0= new QSoundEffect();
QSoundEffect *sound1= new QSoundEffect();
QSoundEffect *sound2= new QSoundEffect();
QSoundEffect *sound3= new QSoundEffect();

reelSounds.append(sound0);
reelSounds.append(sound1);
reelSounds.append(sound2);
reelSounds.append(sound3);

Even if I use it like this(below) in the header file, I get an error.

QVector<QSoundEffect *> reelSounds(4);

Is there a practical style of writing that I can finish in one line?

1

There are 1 best solutions below

0
p-a-o-l-o On

If you want to initialize the vector at header level, in your header:

QVector<QSoundEffect *> reelSounds{new QSoundEffect(), new QSoundEffect(), new QSoundEffect(), new QSoundEffect()};

Slightly more elegant, in your header:

QVector<QSoundEffect *> reelSounds{4};

in source file:

std::generate(reelSounds.begin(), reelSounds.end(), [](){ return new QSoundEffect(); });