Sometimes, programs use counter variables to summarize data, such as the results of a survey. In Fig. 6.8, we used separate counters in our die-rolling program to track the number of occurrences of each side of a die as the program rolled the die 6,000,000 times. An array
version of this program is shown in Fig. 7.10. This version also uses the new C++11 random-number generation capabilities that were introduced in Section 6.8.
1 // Fig. 7.10: fig07_10.cpp
2 // Die-rolling program using an array instead of switch.
3 #include <iostream>
4 #include <iomanip>
5 #include <array>
6 #include <random>
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 const size_t arraySize = 7; // ignore element zero
18 array< unsigned int, arraySize > frequency = {}; // initialize to 0s
19
20 // roll die 6,000,000 times; use die value as frequency index
21 for ( unsigned int roll = 1; roll <= 6000000; ++roll )
22 ++frequency[ randomInt( engine ) ];
23
24 cout << "Face" << setw( 13 ) << "Frequency" << endl;
25
26 // output each array element's value
27 for ( size_t face = 1; face < frequency.size(); ++face )
28 cout << setw( 4 ) << face << setw( 13 ) << frequency[ face ]
29 << endl;
30 } // end main
Face Frequency
1 1000167
2 1000149
3 1000152
4 998748
5 999626
6 1001158
Figure 7.10 uses the array frequency
(line 18) to count the occurrences of each side of the die. The single statement in line 22 of this program replaces the switch statement in lines 23–45 of Fig. 6.8. Line 22 uses a random value to determine which frequency
element to increment during each iteration of the loop. The calculation in line 22 produces a random subscript from 1 to 6, so array frequency
must be large enough to store six counters. However, we use a seven-element array
in which we ignore frequency[0]
—it’s clearer to have the die face value 1 increment frequency[1]
than frequency[0]
. Thus, each face value is used directly as a subscript for array frequency
. We also replace lines 49–54 of Fig. 6.8 by looping through array frequency
to output the results (Fig. 7.10, lines 27–29).
18.218.239.182