Home > C++, VC++, STL > Random shuffling of elements in STL containers

Random shuffling of elements in STL containers

Use stl algorithm random_shuffle. This function has two overloads, first version randomizes using it’s own version of random number generator, second function takes a custom random number generator from our side.

void TestShuffle()
{
    typedef short VT;
    typedef std::vector<vt> VTVector;

    // Count of elements
    const VTVector::size_type Size = 10;

    // Create two vector objects
    VTVector Vect( Size );

    // Generate 10 random numbers
    std::generate( Vect.begin(), Vect.end(), rand );
    // Sort them
    std::sort( Vect.begin(), Vect.end() );
    // Shuffle them to demonstrate shuffle!!!
    std::random_shuffle( Vect.begin(), Vect.end() );
}

//Debugger output after generate call...
//10228,19974,5968,8993,14868,12724,4693,25377,32034,7329
//Debugger output after sort
//4693,5968,7329,8993,10228,12724,14868,19974,25377,32034
//Debugger output after random_shuffle call
//4693,14868,10228,19974,12724,7329,32034,8993,25377,5968

Advertisements
Categories: C++, VC++, STL Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: