How to shuffle a std::vector?
From C++11 onwards, you should prefer:
#include <algorithm>
#include <random>
auto rng = std::default_random_engine {};
std::shuffle(std::begin(cards_), std::end(cards_), rng);
Live example on Coliru
Make sure to reuse the same instance of rng
throughout multiple calls to std::shuffle
if you intend to generate different permutations every time!
Moreover, if you want your program to create different sequences of shuffles each time it is run, you can seed the constructor of the random engine with the output of std::random_device
:
auto rd = std::random_device {};
auto rng = std::default_random_engine { rd() };
std::shuffle(std::begin(cards_), std::end(cards_), rng);
For C++98 you may use:
#include <algorithm>
std::random_shuffle(cards_.begin(), cards_.end());
http://www.cplusplus.com/reference/algorithm/shuffle/
// shuffle algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::shuffle
#include <vector> // std::vector
#include <random> // std::default_random_engine
#include <chrono> // std::chrono::system_clock
int main ()
{
// obtain a time-based seed:
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine e(seed);
while(true)
{
std::vector<int> foo{1,2,3,4,5};
std::shuffle(foo.begin(), foo.end(), e);
std::cout << "shuffled elements:";
for (int& x: foo) std::cout << ' ' << x;
std::cout << '\n';
}
return 0;
}
In addition to what @Cicada said, you should probably seed first,
srand(unsigned(time(NULL)));
std::random_shuffle(cards_.begin(), cards_.end());
Per @FredLarson's comment:
the source of randomness for this version of random_shuffle() is implementation defined, so it may not use rand() at all. Then srand() would have no effect.
So YMMV.