Skip to content

Latest commit

 

History

History
40 lines (23 loc) · 2.38 KB

CppRandomShuffle.md

File metadata and controls

40 lines (23 loc) · 2.38 KB

 

 

 

 

 

 

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