Shuffle a vector in C ++

I have a std :: vector that I need to shuffle. It is only ~ 20 members. In addition, at each start of the program it is also necessary to make different shuffles.

Right now I am using random_shuffle , however it gives the same result every time the program starts. I tried using srand(unsigned(time(NULL))); which was proposed in this , however, which did not work on my platform.

If possible, I want to use only standard code.

Edit: Here is my implementation:

 vector<Tile>gameTiles; gameTiles.push_back(Tile(0,0)); gameTiles.push_back(Tile(0,1)); gameTiles.push_back(Tile(0,2)); gameTiles.push_back(Tile(0,3)); gameTiles.push_back(Tile(0,4)); //etc. ~20 member random_shuffle(gameTiles.begin(), gameTiles.end()); 
+4
source share
2 answers

If srand(unsigned(time(NULL))); doesn't help, then your implementation shouldn't use standard rand() as a random number generator. In this case, there is an alternative version of random_shuffle that accepts its own random number generator. You can simply pass a wrapper around rand() , for example:

 int MyRand(int n) { return std::rand() % n; } // ... std::random_shuffle(bar.begin(), bar.end(), MyRand); // ... 

If you want something with a more even distribution, take a look at the C ++ 11 <random> header.

+10
source

Well, the implementation you give cannot work (you named type foo and used the same literal as the variable). Anyway, try something like this

 // random generator function: ptrdiff_t myrandom (ptrdiff_t i) { return rand()%i;} // pointer object to it: ptrdiff_t (*p_myrandom)(ptrdiff_t) = myrandom; int main(void){ srand(0) vector<Tile>gameTiles; gameTiles.push_back(Tile(0,0)); gameTiles.push_back(Tile(0,1)); gameTiles.push_back(Tile(0,2)); gameTiles.push_back(Tile(0,3)); gameTiles.push_back(Tile(0,4)); random_shuffle(gameTiles.begin(), gameTiles.end(), p_myrandom); } 

It ensures that random_shuffle uses standard rand and that it is initialized correctly. It should give different results if you do not run the application twice in the same second, which will result in using the same seed for rand . The code is right from here , but there is something to change, so I just used it.

0
source

Source: https://habr.com/ru/post/1435620/


All Articles