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.
/*
* C++ Program to demonstrate the random_shuffle() algorithm
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
using namespace std;
void print(vector <string> vs)
{
vector <string>::iterator i;
for(i = vs.begin(); i != vs.end(); i++)
{
cout << setw(2) << *i << " ";
}
cout << endl;
}
int main()
{
string s[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
vector <string> vs(s, s + 13);
cout << "Original order : ";
print(vs);
cout << "Shuffling cards in uniformly random order ... "
<< endl;
random_shuffle(vs.begin(), vs.end());
cout << "Pick any three cards ... " << endl;
cout << "You have got : ";
cout << vs.back() << ", ";
vs.pop_back();
cout << vs.back() << ", ";
vs.pop_back();
cout << vs.back() << endl;
vs.pop_back();
}
$ 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.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Apply for Information Technology Internship
- Practice Computer Science MCQs
- Buy C++ Books
- Buy Programming Books
- Apply for C++ Internship