Figure 6.11 uses the default_random_engine
and the uniform_int_distribution
to roll a six-sided die. Line 14 creates a default_random_engine
object named engine
. Its constructor argument seeds the random-number generation engine with the current time. If you don’t pass a value to the constructor, the default seed will be used and the program will produce the same sequence of numbers each time it executes. Line 15 creates randomInt
—a uniform_int_distribution
object that produces unsigned int
values (as specified by <unsigned int>
) in the range 1 to 6 (as specified by the constructor arguments). The expression randomInt(engine)
(line 21) returns one unsigned int
value in the range 1 to 6.
1 // Fig. 6.11: fig06_11.cpp
2 // Using a C++11 random-number generation engine and distribution
3 // to roll a six-sided die.
4 #include <iostream>
5 #include <iomanip>
6 #include <random> // contains C++11 random number generation features
7 #include <ctime>
8 using namespace std;
9
10 int main()
11 {
12 // use the default random-number generation engine to
13 // produce uniformly distributed pseudorandom int values from 1 to 6
14 default_random_engine engine( static_cast<unsigned int>( time(0) ) );
15 uniform_int_distribution<unsigned int> randomInt( 1, 6 );
16
17 // loop 10 times
18 for ( unsigned int counter = 1; counter <= 10; ++counter )
19 {
20 // pick random number from 1 to 6 and output it
21 cout << setw( 10 ) << randomInt( engine );
22
23 // if counter is divisible by 5, start a new line of output
24 if ( counter % 5 == 0 )
25 cout << endl;
26 } // end for
27 } // end main
2 1 2 3 5
6 1 5 6 4
The notation <unsigned int>
in line 15 indicates that uniform_int_distribution
is a class template. In this case, any integer type can be specified in the angle brackets (<
and >
). In Chapter 18, we discuss how to create class templates and various other chapters show how to use existing class templates from the C++ Standard Library. For now, you should feel comfortable using class template uniform_int_distribution
by mimicking the syntax shown in the example.
3.149.238.159