std::random_shuffle a vector : random_shuffle « STL Algorithms Modifying sequence operations « C++






std::random_shuffle a vector

  
 

#include <iostream>
using std::cout;
using std::endl;

#include <algorithm>
#include <numeric>
#include <vector>
#include <iterator>

int main()
{
   int a1[ 10 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
   std::vector< int > v( a1, a1 + 10 ); // copy of a1
   std::ostream_iterator< int > output( cout, " " );

   cout << "Vector v before random_shuffle: ";
   std::copy( v.begin(), v.end(), output );

   std::random_shuffle( v.begin(), v.end() ); // shuffle elements of v
   cout << "\nVector v after random_shuffle: ";
   std::copy( v.begin(), v.end(), output );
   cout << endl;
   return 0;
}
/* 
Vector v before random_shuffle: 1 2 3 4 5 6 7 8 9 10
Vector v after random_shuffle: 9 2 10 3 1 6 8 4 5 7

 */
        
    
  








Related examples in the same category

1.Use back_insert_iterator to insert element into a vector
2.Use random_shuffle to shuffle all elements randomly
3.Use random_shuffle to shuffle elements with self-written random number generator
4.Randomize elements in a vector with random_shuffle(scores.begin(), scores.end());