Shuffle for cocos2d-x Vector class?

so I tried the std::random_shuffle on the Vector class, but it doesn’t seem to be accepted.

I suggest adding to the Vector class a shuffle method which shuffles the Vector:

could be something like this:

void Vector::shuffle() {
for (int k = 0; k < this->size(); k++) {
int r = k + rand() % (this->size() - k);
this->swap(k, r);
}
}

you need to add algorithm.h for randomshuffle… you tried?

I had included algorithm without .h maybe that was why random_shuffle didn’t work? I was getting some weird errors anyways. But my code above solved the issue. I just think it would be logical for a shuffle function to be added to the Vector class.

cocos2d::Vector only works with cocos2d:s classes as it does some bookkeeping with reference counting. For example this code compiles and links fine (as long as you #include <algorithm> ):

auto sprite = Sprite::create("HelloWorld.png");
cocos2d::Vector<cocos2d::CCSprite*> v;
v.pushBack(sprite);
v.pushBack(sprite);
v.pushBack(sprite);
std::random_shuffle(v.begin(), v.end());

if you want to use primitive types like integers, use std::vector instead.

I like the idea of std::random_shuffle

@slackmoehrle yup it is a lot better than using random numbers :slight_smile: