random_shuffle() Function in C++

«
»
This C++ program demonstrates the random_shuffle() algorithm. The function random_shuffle() shuffles the elements of a container in a uniformly random manner. The function takes two iterators to the beginning and end of the container as parameters. The program creates a set of cards, randomly shuffles and randomly opens three cards from the set.

Here is the source code of the C++ program which demonstrates the random_shuffle() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to demonstrate the random_shuffle() algorithm
  3.  */
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <vector>
  7. #include <iomanip>
  8. using namespace std;
  9.  
  10. void print(vector <string> vs)
  11. {   
  12.     vector <string>::iterator i;
  13.     for(i = vs.begin(); i != vs.end(); i++)
  14.     {
  15.         cout << setw(2) << *i << "  ";
  16.     }
  17.     cout << endl;
  18. }
  19.  
  20. int main()
  21. {
  22.     string s[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
  23.     vector <string> vs(s, s + 13);
  24.  
  25.     cout << "Original order : ";
  26.     print(vs);
  27.     cout << "Shuffling cards in uniformly random order ... "
  28.          << endl;
  29.     random_shuffle(vs.begin(), vs.end());
  30.     cout << "Pick any three cards ... " << endl;
  31.     cout << "You have got   : ";
  32.     cout << vs.back() << ", ";
  33.     vs.pop_back();
  34.     cout << vs.back() << ", ";
  35.     vs.pop_back();
  36.     cout << vs.back() << endl;
  37.     vs.pop_back();
  38. }

$ a.out
Original order :  A   2   3   4   5   6   7   8   9  10   J   Q   K  
Shuffling cards in uniformly random order ... 
Pick any three cards ... 
You have got   : 9, 8, 4

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.