Std::random shuffle
lastmod 2026-11-10created 2015-04-033 edits
std::random_shuffle is a function in the algorithm header of the C++ standard library that randomly shuffles the order of elements within an iterator range. If no random number generator function is passed, implementations usually use std::rand(), so results differ across platforms and quality is not guaranteed; it was deprecated in C++14 and removed in C++17. Use std::shuffle, which takes an engine from the random header (e.g. std::mt19937), instead; when porting existing code, you only need to add a generator object.
random_shuffle example
// random_shuffle example
#include <iostream> // std::cout
#include <algorithm> // std::random_shuffle
#include <vector> // std::vector
#include <ctime> // std::time
#include <cstdlib> // std::rand, std::srand
// random generator function:
int myrandom (int i) { return std::rand()%i;}
int main () {
std::srand ( unsigned ( std::time(0) ) );
std::vector<int> myvector;
// set some values:
for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9
// using built-in random generator:
std::random_shuffle ( myvector.begin(), myvector.end() );
// using myrandom:
std::random_shuffle ( myvector.begin(), myvector.end(), myrandom);
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}