C++ STL algorithm, random_shuffle() program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the C++ random_shuffle() to rearrange a sequence of N elements in a range into one of N! possible arrangements selected at random in C++ programming

To show: How to use the algorithm, random_shuffle() to to rearrange a sequence of N elements in a range into one of N! possible arrangements selected at random in C++ programming

 

// C++ STL algorithm, random_shuffle()

#include <vector>

#include <algorithm>

#include <functional>

#include <iostream>

using namespace std;

 

int main(void)

{

// vector container

vector <int> vec1;

// iterator

vector <int>::iterator Iter1;

int i

 

// push data in range

for(i = 1; i <= 10; i++)

vec1.push_back(i);

cout<<"The original of vector vec1 data: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

 

// randomly shuffle the data

random_shuffle(vec1.begin(), vec1.end());

cout<<"vec1 vector after first time randomly shuffle is: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

make_heap(vec1.begin(), vec1.end());

push_heap(vec1.begin(), vec1.end());

// again

random_shuffle(vec1.begin(), vec1.end());

cout<<"vec1 vector after second time randomly shuffle is: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

// without make_heap(), the debug assertion invalid heap failed invoked

make_heap(vec1.begin(), vec1.end());

push_heap(vec1.begin(), vec1.end());

// and again

random_shuffle(vec1.begin(), vec1.end());

 

cout<<"vec1 vector after third time randomly shuffle is: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

The original of vector vec1 data: 1 2 3 4 5 6 7 8 9 10

vec1 vector after first time randomly shuffle is: 9 2 10 3 1 6 8 4 5 7

vec1 vector after second time randomly shuffle is: 8 2 1 4 5 10 7 3 6 9

vec1 vector after third time randomly shuffle is: 8 2 1 6 3 10 7 4 5 9

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index