Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) 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.

 

#include <algorithm>
#include <iostream>
#include <iterator>
#include <ostream>
#include <vector>

//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"));
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict