Vector getRandomObject always returns the first added element?

Hi!

So, i’ve added these to my vector: [code]void QuizGraphic::initializeDatabase()
{
//Champions

//Ashe
Sprite* ashe = Sprite::createWithSpriteFrameName("ChampSquares/Ashe_Square_0.png");
Champs.pushBack(ashe);

//Aatrox
Sprite* aatrox = Sprite::createWithSpriteFrameName("ChampSquares/Ashe_Square_0.png");
Champs.pushBack(aatrox);

//Draven
Sprite* draven = Sprite::createWithSpriteFrameName("ChampSquares/Draven_Square_0.png");
Champs.pushBack(draven);

//Items

//Abilities

//Ashe q - Frost Shot

}

Sprite* QuizGraphic::getRandChamp()
{

return Champs.getRandomObject()

} [/code]
But when i use it like this: QuizGraphic::initializeDatabase(); Sprite* champ = QuizGraphic::getRandChamp(); champ->setPosition(Vec2(visibleSize.width/2, visibleSize.height/2)); this->addChild(champ, 4);
It always returns the first object??
Why?
Thanks!

Can you show me how you declared Champ?

Maybe use std::shuffle?

Edit: Thinking about this you are probably using cocos2d::Vector, not std::vector?

When getRandomObject is a fun, shouldn't it work as expected...

Thanks!!

When getRandomObject is a fun, shouldn’t it work as expected…

Thanks!!

I should work as expected. If it doesn’t file a bug.

You can do this with normal std::vectors:

 std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 
    std::random_device rd;
    std::mt19937 g(rd());
 
    std::shuffle(v.begin(), v.end(), g);
 
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";

Okay, thanks for you time!

The random function is part of Map, neither Vector nor vector:

  /** 
     * Gets a random object in the map.
     * @return Returns the random object if the map isn't empty, otherwise it returns nullptr.
     */
    V getRandomObject() const
    {
        if (!_data.empty())
        {
            ssize_t randIdx = rand() % _data.size();
            const_iterator randIter = _data.begin();
            std::advance(randIter , randIdx);
            return randIter->second;
        }
        return nullptr;
    }

At multiple calls? After game restart?
Step into the function and check the generated number of the PRNG.

The function is not seeding the pseudo random number generator. It will always generate the same sequence. If the sequence begins with 0, it will always generate 0 at game restart. If you don’t seed the PRNG, it’s seeded with srand(1). This is an overlook with the API design. You need to seed it yourself or use other mechanisms.

1 Like