SeanVanderaa
SeanVanderaa

Reputation: 35

Is there a new way to shuffle an array in C++?

I am relatively new to coding (second semester of C++) and am working on a project where I need to shuffle a string array. I did a similar program in the past using random_shuffle() but have discovered that it has since been deprecated. Are there any other ways I can shuffle an array?

I'm using Xcode BTW, in case that needs to be stated.

Any help is greatly appreciated! This is my first post of many, I'm sure.

Upvotes: 3

Views: 1399

Answers (1)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

std::random_shuffle was deprecated due to its use of the default psuedo random generator, because it was terrible. Now, std::shuffle lets you use c++11's awesome new random device mechanic. You can see that in the overload:

template< class RandomIt, class URBG >
void shuffle( RandomIt first, RandomIt last, URBG&& g );

Where URGB is the randomizer that you want it to use. So now you can just call it like:

std::random_device rd;
std::mt19937 g(rd());
 
std::shuffle(std::begin(my_array), std::end(my_array), g);

And it will be faster and more random then ever.

Upvotes: 3

Related Questions