class MyRandom
1: //random_shuffle2a.cpp
3: #include <iostream>
4: #include <vector>
5: #include <algorithm>
6: using namespace std;
8: //A magical class taken from Nicolai Josuttis' web site:
9: //http://www.josuttis.com/libbook/algo/random1.cpp.html
10: //An object of this class is a suitable function object
11: //for use with this extended version of random_shuffle().
12: //Note that it too uses the built-in rand() function and
13: //defined constant RAND_MAX.
14: class MyRandom
15: {
16: public:
17: ptrdiff_t operator() (ptrdiff_t max)
18: {
19: double tmp;
20: tmp = static_cast<double>(rand())
21: / static_cast<double>(RAND_MAX);
22: return static_cast<ptrdiff_t>(tmp * max);
23: }
24: };
26: int main()
27: {
28: cout << "\nThis program illustrates the use of the STL "
29: "random_shuffle() algorithm\n(extended version) to "
30: "randomize the order of values in a vector of integers, "
31: "\nthis time with the aid of a programmer-supplied "
32: "pseudorandom number generator.";
33: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
35: int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
36: vector<int> v(a, a+10);
38: cout << "\nHere are the values in the vector:\n";
39: for (vector<int>::size_type i=0; i<v.size(); i++)
40: cout << v.at(i) << " ";
41: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
43: cout << "\nNow we randomize the order of the values.";
44: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
45: MyRandom generator;
46: random_shuffle(v.begin(), v.end(), generator);
48: cout << "\nHere are the revised contents of the vector:\n";
49: for (vector<int>::size_type i=0; i<v.size(); i++)
50: cout << v.at(i) << " ";
51: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
52: }