Back to Richel Bilderbeek's homepage.

Back to Richel Bilderbeek's Code Snippets.

 

 

 

RandomShuffle

 

The algorithm to shuffle a std::vector to a random order is already present in the STL. It is called std::random_shuffle and can be found in the header file algorithm.

 

Code in plain text can be found here.

 

 

#include <iostream>

#include <algorithm>

#include <vector>

#include <ostream>

#include <iterator>

 

//From http://www.richelbilderbeek.nl/CppRandomShuffle.htm

int main()

{

//Create a std::vector

std::vector<int>(v);

//Fill it with 10 values

for (int i=0; i!=10; ++i) v.push_back(i);

//Show it on screen

std::cout << "Before shuffling: " << std::endl;

std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout,"\n"));

//Shuffle it

std::random_shuffle(v.begin(),v.end());

//Show it on screen

std::cout << "After shuffling: " << std::endl;

std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout,"\n"));

//Wait for a key

std::cin.get();

}

 

 

Back to Richel Bilderbeek's Code Snippets.

Back to Richel Bilderbeek's homepage.