Compartir a través de


random_shuffle

Rearranges a sequence of N elements in a range into one of N! possible arrangements selected at random.

template<class RandomAccessIterator>
   void random_shuffle(
      RandomAccessIterator _First, 
      RandomAccessIterator _Last
   );
template<class RandomAccessIterator, class RandomNumberGenerator>
   void random_shuffle(
      RandomAccessIterator _First, 
      RandomAccessIterator _Last, 
      RandomNumberGenerator& _Rand
   );

Parameters

  • _First
    A random-access iterator addressing the position of the first element in the range to be rearranged.

  • _Last
    A random-access iterator addressing the position one past the final element in the range to be rearranged.

  • _Rand
    A special function object called a random number generator.

Remarks

The two versions of the function differ in how they generate random numbers. The first version uses an internal random number generator and the second a random number generator function object that is explicitly passed and can accept a seed value.

Example

// alg_random_shuffle.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>

int main( ) {
   using namespace std;
   vector <int> v1;
   vector <int>::iterator Iter1, Iter2;

   int i;
   for ( i = 1 ; i <= 9 ; i++ )
      v1.push_back( i );

   random_shuffle( v1.begin( ), v1.end( ) );
   cout << "The original version of vector v1 is: ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")." << endl;

   // Shuffled once
   random_shuffle( v1.begin( ), v1.end( ));
   push_heap( v1.begin( ), v1.end( ) );
   cout << "Vector v1 after one shuffle is:       ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")." << endl;

   // Shuffled again
   random_shuffle( v1.begin( ), v1.end( ));
   push_heap( v1.begin( ), v1.end( ) );
   cout << "Vector v1 after another shuffle is:   ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")." << endl;
}

Sample Output

The original version of vector v1 is: ( 9 2 7 3 1 6 8 4 5 ).
Vector v1 after one shuffle is:       ( 1 4 7 9 2 5 8 6 3 ).
Vector v1 after another shuffle is:   ( 3 2 8 5 4 9 6 7 1 ).

Requirements

Header: <algorithm>

Namespace: std

See Also

Reference

Predicate Version of random_shuffle

random_shuffle (STL Samples)

Standard Template Library

Other Resources

<algorithm> Members