    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Code Critique Competition 110</title>
        <link>https://members.accu.org/index.php/articles/2476</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">ACCU Topics + Student Code Critiques from CVu journal. + CVu Journal Vol 30, #1 - March 2018</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c184/">Journal Columns</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c183/">Code Critique</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c383/">301</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c13-183-383/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c13+183+383/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Code Critique Competition 110</h1>
<p><strong>Author:</strong>&nbsp;Bob Schmidt</p>
<p>
<strong>Date:</strong> 04 March 2018 00:00:00 +00:00 or Sun, 04 March 2018 00:00:00 +00:00</p>
<p><strong>Summary:</strong>&nbsp;Set and collated by Roger Orr. A book prize is awarded for the best entry.</p>
<p><strong>Body:</strong>&nbsp;<p class="EditorIntro">Please note that participation in this competition is open to all members, whether novice or expert. Readers are also encouraged to comment on published entries, and to supply their own possible code samples for the competition (in any common programming language) to scc@accu.org.</p>

<p class="EditorIntro">Note: If you would rather not have your critique visible online, please inform me. (Email addresses are not publicly visible.)</p>

<h2>Last issueâ€™s code</h2>

<p>Thanks to Jason Spencer for the random number generator suggestion leading to this issueâ€™s critique!</p>

<p class="blockquote">Iâ€™m trying to write a very simple dice game where the computer simulates two players each throwing dice. The higher score wins and after a (selectable) number of turns the player whoâ€™s won most times wins the game. (Iâ€™m going to make the game cleverer once itâ€™s working.) But the games always seem to be drawn and I canâ€™t see why. Here is what the program produces:</p>

<pre class="programlisting">
    dice_game
    Let's play dice
    How many turns? 10
    Drawn!
    How many turns? 8
    Drawn!
    How many turns? ^D</pre>

<p>Whatâ€™s going wrong, and how might you help the programmer find the problem? As usual, there may be other suggestions you might make of some other possible things to (re-)consider about their program.</p>

<ul>
	<li>Listing 1 contains <span class="filename">zipit.h</span></li>
	<li>Listing 2 contains <span class="filename">dice game.cpp</span></li>
</ul>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
// Class to 'zip' together a pair of iterators
template &lt;typename T&gt;
class zipit : public std::pair&lt;T, T&gt;
{
  zipit &amp;operator+=(std::pair&lt;int,int&gt; const &amp;rhs)
  {
    this-&gt;first += rhs.first;
    this-&gt;second += rhs.second;
    return *this;
  }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public:
  using std::pair&lt;T, T&gt;::pair;
  zipit &amp;operator+=(int n)
  {
    return *this += std::make_pair(n, n);
  }
  zipit &amp;operator-=(int n)
  {
    return *this += std::make_pair(-n, -n);
  }
  zipit &amp;operator++()
  {
    return *this += 1;
  }
  zipit &amp;operator--()
  {
    return *this += -1;
  }
  auto operator*()
  {
    return std::make_pair(
      *this-&gt;first, *this-&gt;second);
  }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<h2>Critiques</h2>

<h3>James Holland</h3>

<p>In <code>main()</code>, the user has created an object named <code>generator</code> of type <code>randomize</code> and then has sensibly passed it by reference to <code>play()</code>. Within <code>play()</code> the <code>randomize</code> object is then passed to the two <code>generate()</code> functions by value. Passing by value makes a copy of the object and this where problems begin. The <code>randomize</code> objects contain state that is used in a predetermined way to generate the pseudo random numbers. Two <code>randomize</code> objects that start in the same state will produce the same sequence of numbers. The two calls to <code>generate()</code> each make use of identical copies of <code>randomize</code> and so both will produce exactly the same sequence of random numbers. This is why all runs of the dice game end in a draw.</p>

<p>What we would like to happen is for both calls of <code>generate()</code> to use the same <code>randomize</code> object. In this way when one call to <code>generate()</code> has obtained a set of random numbers, the other call to <code>generate()</code> will continue to use the same <code>randomize</code> object and so will obtain a different sequence of numbers.</p>

<p>One way to achieve this is to pass the <code>randomize</code> object to <code>generate()</code> by reference thus ensuring there is only ever one <code>randomize</code> object. This can be done by employing the standard library reference wrapper <code>ref()</code>. This wrapper conveys references to function templates that take the parameters by value. Fortunately, <code>generate()</code> is such a function. The calls to <code>generate()</code> simply become as shown below.</p>

<pre class="programlisting">
  std::generate(player1.begin(), player1().end(),
    std::ref(generator);
  std::generate(player2.begin(), player2().end(),
    std::ref(generator);</pre>
	
<p>While we are talking about random number generators, it is recommended not to use one of the standard library generators, such as <code>MT19937</code>, on its own but instead to use it with a distribution, also available from the standard library. There are problems associated with dividing the output from a generator by a constant and taking the reminder. Using a distribution will ensure a high quality series of random numbers.</p>

<p>Running <code>dice_game</code> will now probably produce the desired result. I say â€˜probablyâ€™ because the studentâ€™s software contains a serious flaw. The free functions <code>begin()</code> and <code>end()</code> pass their values by value. This means their parameters are copied. The functions <code>begin()</code> and <code>end()</code> construct a <code>zipit</code> object from iterators that point to copies of <code>player1</code> and <code>player2</code> arrays. When the functions return, the copies of <code>player1</code> and <code>player2</code> will be destroyed. The <code>zipit</code> object will be returned to its caller but the iterators it contains will be invalid as they point to objects that no longer exist. It may be the case that the memory locations where the copies of <code>player1</code> and <code>player2</code> existed maintain their values for as long as the program requires them. It is in this way that the program appears to work correctly. The behaviour of software should not be left to chance and so this bug must be corrected. Fortunately, this is a relatively simple matter.</p>

<p>Instead of passing <code>player1</code> and <code>player2</code> to <code>begin()</code> and <code>end()</code> by value, they should be passed by reference. In this way no copies are made and the iterators returned in the <code>zipit</code> object will point to the original (and still existing) versions of <code>player1</code> and <code>player2</code>. The program is now running with a firm footing!</p>

<p>Although the software now works correctly, it seems quite complicated for what it does. Perhaps there is another way of structuring the program that is shorter and easier to understand. The studentâ€™s software involves the creation of two vectors that contain the results of rolling the dice, one for each of the players. There is also quite an elaborate arrangement of operator functions that are required to manipulate iterators that point to the two vectors. Instead of having a pair of vectors, each element of which contains a single value, I propose having a single vector that contains a pair of dice values, one for each player. Iterating through a single vector is much simpler that trying to iterate through two vectors at the same time. There is no danger of getting out of step. I suggest my version of the software is also considerably simpler as none of the code within <span class="filename">zipit.h</span> is required. I have kept the interface to <code>Play()</code> the same as in the studentâ€™s code and so <code>main()</code> can remain the same. I have modified the <code>Randomize</code> class to take advantage of the standard libraryâ€™s uniform integer distribution as shown below.</p>

<pre class="programlisting">
  #include &lt;algorithm&gt;
  #include &lt;functional&gt;
  #include &lt;iostream&gt;
  #include &lt;random&gt;
  #include &lt;vector&gt;
  class Randomize
  {
    public:
    Randomize():d(1, 6){}
    std::pair&lt;int, int&gt; operator()()
    {
      return {d(e), d(e)};
    }
    private:
    std::mt19937 e;
    std::uniform_int_distribution&lt;&gt; d;
  };
  void play(int turns, Randomize &amp; generator)
  {
    std::vector&lt;std::pair&lt;int, int&gt;&gt;
      players(turns);
    std::generate(players.begin(),
      players.end(), std::ref(generator));
    int total{};
    for (const auto &amp; turn : players)
    {
      const auto p1_score = turn.first;
      const auto p2_score = turn.second;
      if (p1_score != p2_score)
      {
        const auto diff = p1_score - p2_score;
        total += diff &gt; 0 ? 1 : -1;
      }
    }
    if (total &gt; 0)
    {
      std::cout &lt;&lt; &quot;Player 1 wins\n&quot;;
    }
    else if (total &lt; 0)
    {
      std::cout &lt;&lt; &quot;Player 2 wins\n&quot;;
    }
    else
    {
      std::cout &lt;&lt; &quot;Drawn!\n&quot;;
    }
  }
  int main()
  {
    Randomize generator;
    int turns;
    std::cout &lt;&lt; &quot;Let's play dice\n&quot;;
    while (std::cout &lt;&lt; &quot;How many turns? &quot;,
      std::cin &gt;&gt; turns)
    {
      play(turns, generator);
    }
  }</pre>
  
<p><code>Randomize</code> now simulates rolling the dice for both players within one call of <code>operator()()</code>. I felt that <code>copysign()</code> is a slightly strange function to use in this context as it converts its integer parameters to <code>double</code>s before copying the sign of the second parameter to the first. The resulting double is then converted back to an integer when added to <code>total</code>. The same effect can be simply achieved by a conditional operator as I have used. No conversion to and from <code>double</code> is required.</p>

<h3>Paul Floyd</h3>

<p>There are two main problems with this code. The first is the cause of the draws, the second results in crashes.</p>

<p>For the cause of the draws, we have a misuse of the interface of <code>std::generate</code>:</p>

<pre class="programlisting">
  template&lt; class ForwardIt, class Generator &gt;
  void generate( ForwardIt first,
    ForwardIt last, Generator g );</pre>
	
<p>(from http://en.cppreference.com/w/cpp/algorithm/generate)</p>

<p>So in the original code, where the call to this is </p>

<pre class="programlisting">
  std::generate(player1.begin(),
    player1.end(), generator);
  std::generate(player2.begin(),
    player2.end(), generator);</pre>
	
<p>then the variable <code>generator</code> is passed to <code>std::generate</code> by value (the template deduces a type of <code>randomize</code>).</p>

<p>This is borne out by <code>nm</code> (output slightly reformatted for printing):</p>

<pre class="programlisting">
  nm -C cc109 | grep generate
  00000000004013d3 W void std::generate
  &lt;__gnu_cxx::__normal_iterator&lt;int*,
   std::vector&lt;int, std::allocator&lt;int&gt;&gt;&gt;,
   randomize&gt;(
    __gnu_cxx::__normal_iterator&lt;int*,
    std::vector&lt;int, std::allocator&lt;int&gt;&gt;&gt;,
    __gnu_cxx::__normal_iterator&lt;int*,
    std::vector&lt;int, std::allocator&lt;int&gt;&gt;&gt;,
    randomize)</pre>
	
<p>This means that the original copy does not get updated by the first call, so the second call to <code>std::generate</code> gets a copy of the same object. The fix for this would be either to make the call to the template function explicit (not nice) or to just use <code>std::ref</code> so that the template will be initialised with a reference type rather than passing by value. Now with a reference the variable <code>generator</code> does have its state modified by the first call.</p>

<p>Hereâ€™s <code>nm</code> again when using <code>std::ref</code>:</p>

<pre class="programlisting">
  nm -C cc109 | grep generate
  00000000004013ca W void std::generate
  &lt;__gnu_cxx::__normal_iterator&lt;int*,
   std::vector&lt;int, std::allocator&lt;int&gt;&gt;&gt;,
   std::reference_wrapper&lt;randomize&gt;&gt;(
    __gnu_cxx::__normal_iterator&lt;int*, 
    std::vector&lt;int, std::allocator&lt;int&gt;&gt;&gt;,
    __gnu_cxx::__normal_iterator&lt;int*, 
    std::vector&lt;int, std::allocator&lt;int&gt;&gt;&gt;,
    std::reference_wrapper&lt;randomize&gt;)</pre>
	
<p>At first I thought that was the end of the story. But then I ran the code through AddressSanitizer (compiled with clang++ and the <code>-fsanitize=address</code> option), and I saw:</p>

<pre class="programlisting">
Let's play dice
How many turns? 10
===================================================
==2657==ERROR: AddressSanitizer: heap-use-after-free on address 0x6040000003d0 at pc 0x0001085aeca3 bp 0x7ffee7654010 sp 0x7ffee7654008
READ of size 4 at 0x6040000003d0 thread T0
    #0 0x1085aeca2 in zipit&lt;std::__1::__wrap_iter&lt;int*&gt; &gt;::operator*() .zipit.h:32
    #1 0x1085ad4f0 in play(int, randomize&amp;) dice_game.cpp:30
    #2 0x1085af3e6 in main dice_game.cpp:59
    #3 0x7fff5c710114 in start (libdyld.dylib:x86_64+0x1114)
0x6040000003d0 is located 0 bytes inside of 40-byte region [0x6040000003d0,0x6040000003f8)
freed by thread T0 here:
    #0 0x1086226ab in wrap__ZdlPv (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x646ab)
    #1 0x1085af8f4 in std::__1::__vector_base&lt;int, std::__1::allocator&lt;int&gt; &gt;::~__vector_base() vector:445
    #2 0x1085af4c4 in std::__1::vector&lt;int, std::__1::allocator&lt;int&gt; &gt;::~vector() iterator:1386
    #3 0x1085ae384 in std::__1::vector&lt;int, std::__1::allocator&lt;int&gt; &gt;::~vector() iterator:1386
    #4 0x1085ad0b5 in play(int, randomize&amp;) dice_game.cpp:27
    #5 0x1085af3e6 in main dice_game.cpp:59
    #6 0x7fff5c710114 in start (libdyld.dylib:x86_64+0x1114)

previously allocated by thread T0 here:
    #0 0x1086220ab in wrap__Znwm (libclang_rt.asan_osx_dynamic.dylib:x86_64h+0x640ab)
    #1 0x1085b0279 in std::__1::vector&lt;int, std::__1::allocator&lt;int&gt; &gt;::allocate(unsigned long) vector:925
    #2 0x1085b2631 in std::__1::vector&lt;int, std::__1::allocator&lt;int&gt; &gt;::vector(std::__1::vector&lt;int, std::__1::allocator&lt;int&gt; &gt; const&amp;) vector:1200
    #3 0x1085ae35c in std::__1::vector&lt;int, std::__1::allocator&lt;int&gt; &gt;::vector(std::__1::vector&lt;int, std::__1::allocator&lt;int&gt; &gt; const&amp;) vector:1193
    #4 0x1085acfcd in play(int, randomize&amp;) dice_game.cpp:27
    #5 0x1085af3e6 in main dice_game.cpp:59
    #6 0x7fff5c710114 in start (libdyld.dylib:x86_64+0x1114)</pre>
	
<p>So there is an error in the dereference operator for a vector that is created and destroyed on the same line. That smells like a local variable being created and destroyed.</p>

<p>The problem is with the zipit <code>begin()</code> and <code>end()</code> functions.</p>

<pre class="programlisting">
  template &lt;typename T&gt;
  auto begin(T one, T two)
    -&gt; zipit&lt;typename T::iterator&gt;
  â€¦</pre>
  
<p>This is instantiated here</p>

<pre class="programlisting">
  for (auto it = begin(player1, player2);</pre>
  
<p>Where <code>player1</code> and <code>player2</code> are the vectors of <code>int</code>. So <code>T</code> is a vector of <code>int</code>, and <code>one</code> and <code>two</code> are passed by copy. The local copy gets destroyed at the end of the call, leaving the returned pair of iterators dangling.</p>

<p>A third opinion from <code>nm</code>:</p>

<pre class="programlisting">
  nm -C cc109 | grep begin
  00000000004015a0 W zipit&lt;std::vector&lt;int,
    std::allocator&lt;int&gt;&gt;::iterator&gt;
  begin&lt;std::vector&lt;int, std::allocator&lt;int&gt;&gt;&gt;(
    std::vector&lt;int, std::allocator&lt;int&gt;&gt;,
    std::vector&lt;int, std::allocator&lt;int&gt;&gt;)
  0000000000401b9c W std::vector&lt;int, 
    std::allocator&lt;int&gt;&gt;::begin() const
  0000000000401356 W std::vector&lt;int, 
    std::allocator&lt;int&gt;&gt;::begin()</pre>
	
<p>The fix for this is to make the <code>begin</code>/<code>end</code> arguments references:</p>

<pre class="programlisting">
  template &lt;typename T&gt;
  auto begin(T&amp; one, T&amp; two)
    -&gt; zipit&lt;typename T::iterator&gt;
  {
    return {one.begin(), two.begin()};
  }
  template &lt;typename T&gt;
  auto end(T&amp; one, T&amp; two)
    -&gt; zipit&lt;typename T::iterator&gt;
  {
    return {one.end(), two.end()};
  }</pre>
  
<p>OK, now for the minor nits. I get a warning about the unused <code>cout</code> in the <code>while</code> condition. This can be silenced by a cast</p>

<pre class="programlisting">
  while((void)(std::cout &lt;&lt; &quot;How many turns? &quot;),
    std::cin &gt;&gt; turns)
    {
      play(turns, generator);
    }
  }</pre>
  
<p>A bit ugly.</p>

<p>There are no include guards, and the cpp file does not include <span class="filename">zipit.h</span> before the other files. This means that users that include <span class="filename">zipit.h</span> will have the misfortune of playing â€˜guess the header dependencyâ€™ (or fixing the header).</p>

<p>Lastly, the read of the <code>int</code> for the number of turns does not prevent against reading negative values. This then gets converted to <code>size_t</code> in the vector constructor. If the allocation succeeds then itâ€™s going to be a very long game. </p>

<h3>Russel Winder</h3>

<p>First and foremost why try to invent a custom zip capability, and risk getting it wrong? Where are the tests? I am sure there is a good criticism to be made of the code in <span class="filename">zipit.h</span>, but I shall just circumvent all that and say: use <code>boost::combine</code> to undertake the zip and delete <span class="filename">zipit.h</span>.</p>

<p>The original code also has output scattered around. OK so only in two functions, but still, the design principle applies: keep all input and output in one place and have functions return values to represent the result. Doing this enhances testability, so must be a good thing. In this case <code>play</code> should not do output but should return a â€˜who wonâ€™ result. Seems like a good place for an enumerated type. The output of the result then happens in <code>main</code>.</p>

<p>So ignoring the time it took to make those changes and get the code to actually work (because the developer failed to read the documentation correctly), we find it still delivers a draw in all cases. A bit of a WTF moment, but surely one it was intended one would have. So what is the problem? If you print out the value of the two <code>std::vector</code>s of rolls, you find that you always get the same sequence of values. Always. Fairly obvious then the same start state is the case for all calls to the Mersenne Twister generator. It turns out that <code>std::generate</code> seems to clone the generator passed so the player1 generation and the player2 generation are identical since the <code>randomize</code> class creates a new generator for each instance initialised exactly the same. A cure for this is to make the <code>mt</code> instance shared by making it static. Since this is a single threaded application this does not seem to be a problem, even if global shared state is deemed anathema by some.</p>

<p>With this change in place, and resulting in the program shown in Listing 1, the program seems to work as originally intended.</p>

<p>Of course, one has yet again to ask the question whether C++ is the best programming language to use for this application. Let us assume no. So what to choose? Well to investigate this letâ€™s look at Python, D and Rust.</p>

<p>Python, see Listing 2, has a built in <code>zip</code> function. Also the <code>sum</code> function acting over an iterable makes for a much nicer expression of the core part of the algorithm - which is rolling the dice and checking for who wins. Even though Python is a dynamic language at run time, type annotations have been used so that using the mypy command, we can be sure that all the function calls are correctly statically typed. The random numbers are provided via the <code>random</code> package, using a Mersenne Twister algorithm, which is â€˜globalâ€™ so there are no problems about generating the same sequence of random numbers. It would seem that Python makes it harder to make errors in this sort of application.</p>

<p>D, see Listing 3, also has a builtin <code>zip</code> function, so no difficulties on that front. Comparing the C++, Python, and D, one gets the sneaking suspicion that D is the best language for writing this code: less faff. Well except maybe for the random number generator. Rather than using a random number generator creating integers from the set {1, 2, 3, 4, 5, 6} with each integer result assumed to have equal probability, The <code>std.random</code> <code>dice</code> function is used to create a random number generator of the values with an explicit probability. Equal probabilities are used here, but it allows for experimentation with â€˜loaded diceâ€™. Another â€˜featureâ€™ of the code worth noting is the function call chaining approach as opposed to function application as used in C++ and Python. This is blurring the â€˜function applicationâ€™ and â€˜method call on an objectâ€™ that is quite rigid in C++ and Python. It is an aspect of trying to be as declarative as possible in what is an imperative language.</p>

<p>Of course Rust, see Listing 4, is reputedly the language of the moment, set to replace C, and perhaps C++, as the language of first choice for new projects. Immediately obvious is the very different way enumerations work. C++, Python, and D have very similar ways of defining and working with enumerations, Rust takes a very different approach. In particular an enumeration value can carry data of undefined value, just defined type. Rust, like D, emphasises being declarative, hence the creation of pipelines of data manipulation as seen in the D code. Of course Rust tries to go further and mandates the use of monads to create what is arguably a functional programming language (disguising the imperative language). This is seen most clearly in <code>main</code>. The code seems to a bit bigger, but there an appeal that error handling is enforced but in a quite pleasing way; especially highlighting the nice use of enumerations.. After the interesting dice emulation of D, in this Rust code returns to the generate an integer in a range assuming equal probabilities. The random number generator is not global, but it is shared, so no possibility of generating the same sequence for each player.</p>

<p>So is C++ the best language for this application? Probably not, but for something like this using the language you are most â€˜at homeâ€™ with is likely the best choice. Unless you are challenging yourself as a programmer by using a programming language you are not entirely familiar with. Personally I quite favour the D code.</p>

<p>Why is Go not in this list of languages likely to be better than C++? It should be, but I ran out of time to complete that version of the code. Bad project management I admit.</p>

<p><em>Nota bene</em>: the code presented here does not represent a reasonable formatting of the code, and indeed violates many <em>de facto</em> and <em>de jure</em> code formatting guidelines. However, the journal formatting structure requires badly formatted code to be presented. :-(</p>

<p>PS There is clearly a difference in the languages behaviour here since the different languages produce different frequencies of draws. Hummmâ€¦ <p class="blockquote">[Editor: since the programs all model the same die throwing game then statistically significant differences imply at least one is buggy.]</p>
</p>

<h4>Listing 1</h4>

<pre class="programlisting">
#include &lt;algorithm&gt;
#include &lt;chrono&gt;
#include &lt;iostream&gt;
#include &lt;numeric&gt;
#include &lt;random&gt;
#include &lt;boost/range/combine.hpp&gt;
#include &lt;boost/tuple/tuple.hpp&gt;
class randomize {
  private:
    static std::mt19937 mt;
  public:
    int operator()() { return mt() % 6 + 1; }
};
std::mt19937 randomize::mt {
  (unsigned long int)std::chrono::system_clock::now()
  .time_since_epoch()
  .count()
};

enum class result {
  draw = 0,
  player1_win = 1,
  player2_win = 2,
};
typedef boost::tuple&lt;int, int&gt; int_pair;
result play(int const turns, randomize &amp; generator) {
  std::vector&lt;int&gt; player1(turns);
  std::vector&lt;int&gt; player2(turns);
  std::generate(player1.begin(), player1.end(), generator);
  std::generate(player2.begin(), player2.end(), generator);
  auto pairs = boost::combine(player1, player2);
  int_pair const t_t = std::accumulate(
    pairs.begin(),
    pairs.end(),
    int_pair{0, 0},
    [](int_pair t, int_pair i) {
      int a, b;
      boost::tie(a, b) = i;
      return int_pair{
      boost::get&lt;0&gt;(t)
        + (a &gt; b ? 1 : (a &lt; b ? -1 : 0)),
                    0};
            });
    int const total = boost::get&lt;0&gt;(t_t);
    return total == 0
      ? result::draw
      : (total &gt; 0 ? result::player1_win 
      : result::player2_win);
}
int main() {
    randomize generator;
    int turns;
    std::cout &lt;&lt; &quot;Let's play dice&quot; &lt;&lt; std::endl;
    while (
            std::cout &lt;&lt; &quot;How many turns? &quot;,
            std::cin &gt;&gt; turns) {
        auto const result = play(turns, generator);
        if (result == result::draw) {
            std::cout &lt;&lt; &quot;Drawn!&quot; &lt;&lt; std::endl;
        } else {
            std::cout
              &lt;&lt; &quot;Player &quot;
              &lt;&lt; (int)result
              &lt;&lt; &quot; wins&quot;
              &lt;&lt; std::endl;
        }
    }
}</pre>

<h4>Listing 2</h4>

<pre class="programlisting">
#!/usr/bin/env python3
from enum import Enum
import random
from typing import Tuple
class Result(Enum):
    draw = 0
    player1_win = 1
    player2_win = 2
def player1_win(p: Tuple[int, int]) -&gt; int:
    if p[0] &gt; p[1]:
        return 1
    elif p[0] &lt; p[1]:
        return -1
    return 0
def play(turns: int, gen) -&gt; Result:
    player1_wins = sum(
        player1_win(p) for p in zip(
            (gen() for _ in range(turns)),
            (gen() for _ in range(turns))
        ))
    if player1_wins &gt; 0:
        return Result.player1_win
    elif player1_wins &lt; 0:
        return Result.player2_win
    return Result.draw
def main() -&gt; None:
    print(&quot;Let's play dice&quot;)
    random.seed()
    while True:
        try:
            turns = int(input('How many turns? '))
        except ValueError:
            return
        result = play(
            turns,
            lambda: random.randint(1, 6)
        )
        if result == Result.draw:
            print('Drawn!')
        else:
            print('Player {} wins.'.format(result.value))
if __name__ == '__main__':
    try:
        main()
    except (EOFError, KeyboardInterrupt):
        print()</pre>

<h4>Listing 3</h4>

<pre class="programlisting">
#!/usr/bin/env rdmd
import std.algorithm: map, sum;
import std.array: array;
import std.conv: to;
import std.random: dice;
import std.range: iota, zip;
import std.stdio: readln, write, writefln, writeln;
import std.string: strip;
enum Result {
    draw = 0,
    player1_win = 1,
    player2_win = 2,
}
Result play(uint turns, uint delegate(uint) generator) {
    auto player1_wins =
      zip(
          iota(turns).map!generator(),
          iota(turns).map!generator())
      .map!&quot;a[0] &gt; a[1] ? 1 : (a[0] &lt; a[1] ? -1 : 0)&quot;
      .sum;
    return player1_wins == 0
      ? Result.draw
      :  player1_wins &gt; 0
         ? Result.player1_win
         : Result.player2_win;
}
void main() {
    writeln(&quot;Let's play dice&quot;);
    try {
        while (true) {
            write(&quot;How many turns? &quot;);
            uint turns = to!uint(readln().strip());
            auto result = play(turns, delegate uint(uint) {
                    return to!uint(
                            dice(0.0,
                                 16.67,
                                 16.67,
                                 16.67,
                                 16.67,
                                 16.67,
                                 16.67));
                });
            if (result == Result.draw) {
                writeln(&quot;Drawn!&quot;);
            } else {
                writefln(&quot;Player %d wins.&quot;, result);
            }
        }
    } catch (Exception) {
        writeln();
    }
}</pre>

<h4>Listing 4</h4>

<pre class="programlisting">
extern crate itertools;
extern crate rand;
use std::io::{self, Write};
use itertools::Itertools;
use rand::distributions::{Range, Sample};
enum Result {
    PlayerWon(u8),
    Draw
}
fn play(
    turns: u32,
    dice_roll: &amp;mut FnMut()-&gt;u8) -&gt; Result
{
    let player1_wins: i32 =
        itertools::repeat_call(dice_roll)
        .tuples::&lt;(_, _)&gt;()
        .map(|p|
             if p.0 &gt; p.1 { 1 }
             else if p.0 &lt; p.1 { -1 }
             else { 0 }
        )
        .take(turns as usize)
        .sum();
    if player1_wins != 0 {
        Result::PlayerWon(
            if player1_wins &gt; 0 { 1 }
            else { 2 }
        )
    }
    else { Result::Draw }
}
fn main() {
    println!(&quot;Let's play dice&quot;);
    let mut dice = Range::new(1u8, 7u8);
    let mut rng = rand::thread_rng();
    let mut buffer = String::new();
    loop {
        print!(&quot;How many turns? &quot;);
        io::stdout()
            .flush()
            .expect(&quot;Could not flush stdout.&quot;);
        buffer.clear();
        match io::stdin().read_line(&amp;mut buffer) {
            Ok(_) =&gt; match buffer.trim().parse::&lt;u32&gt;() {
                Ok(turns) =&gt; match play(
                    turns,
                    &amp;mut ||{ dice.sample(&amp;mut rng) }
                ) {
                    Result::PlayerWon(p) =&gt;
                        println!(&quot;Player {} wins.&quot;, p),
                    Result::Draw =&gt;
                        println!(&quot;Drawn!&quot;),
                },
                Err(_) =&gt; break
            },
            Err(_) =&gt; break
        }
    }
}</pre>

<h3>Jason Spencer</h3>

<p>The reason for all games ending in a draw is that the random number generator actually creates a deterministic sequence of numbers, and since the calls to <code>std::generate</code> copy the generator object, that is to say its internal state, the die throws generated for both players are identical. There is, however, another bug with invalidated iterators that potentially corrupts the result calculation, and may cause a crash or non-draw result.</p>

<p>The issues with the code are as follows:</p>

<h4>zipit.h</h4>

<ul>
	<li>The file requires the following includes: <code>&lt;utility&gt;</code> for <code>std::pair</code> and <code>std::make_pair</code>. Also  <code>&lt;iterator&gt;</code> for <code>std::advance</code>, <code>std::begin</code> and <code>std::end</code>, which will be added next. An include guard for the whole file is also a good idea.</li>
	
	<li>class <code>zipit</code> is derived from <code>std::pair&lt;T,T&gt;</code> with public access. Consider making it protected, otherwise a user can access <code>.first</code> and <code>.second</code> and change their values, putting them out of sync. This might be a wanted behaviour, however. I think it breaks encapsulation and the inheritance should be protected.</li>
	
	<li>Consider renaming the template parameter from <code>T</code> to <code>Iter</code>, to express the meaning. <code>T</code> is used so often that it can get confusing.</li>
	
	<li>Two <code>operator*</code> functions (one const, one non-const) arenâ€™t required, only one â€“ the function doesnâ€™t change the <code>zipit</code> instance â€“ although dereferencing may then lead to a change in the pointed to variable, but that doesnâ€™t mean the <code>zipit</code> instance changes (compare <code>const char * ptr</code> and <code>char * const ptr</code>). So only the const version is needed, and the non-const should be removed.</li>
	
	<li><code>operator*</code> at the moment returns an rvalue, so <code>zipit</code> only models an input iterator. We may want to return an lvalue to model an output iterator. See the discussion and implementation later.</li>
	
	<li><code>zipit &amp;operator+=(std::pair&lt;int,int&gt; const &amp;rhs)</code> should use <code>std::advance</code> instead of <code>+=</code> to advance <code>this-&gt;first</code> and <code>this-&gt;second</code>. If the underlying iterator is not a random access iterator it may not have an <code>operator+=</code> overload. <code>std::advance</code> will either use <code>operator++</code> or <code>operator+=</code>, preferring the latter as it has constant time complexity, while the former is linear.</li>
	
	<li><code>operator-&gt;</code> is indeed required to at least satisfy the requirements of <code>InputIterator</code> (see later for discussion of iterator types).</li>
	
	<li>The <code>begin(T,T)</code> and <code>end(T,T)</code> free functions should both have their arguments passed by non-const reference. Both of the functions extract iterators from the arguments passed and store them in a <code>zipit</code> instance and return that. However, since the arguments passed to these functions are currently temporary copies the iterators are invalid as soon as the function returns. Since the score is later calculated from dice throws stored in memory that has been deallocated the program either crashes or has invalid results.</li>
	
	<li>In <code>begin(T,T)</code> and <code>end(T,T)</code> the use of <code>T::iterator</code> assumes that the typedef exists in <code>T</code>. By using <code>std::begin(one)</code> instead of <code>one.begin()</code> and changing the return type of these functions they can be adapted to also support C-style arrays, thusly (just s/begin/end/g for the <code>end</code> function):</li>
</ul>

<pre class="programlisting">
    template &lt;typename T&gt;
    auto begin(T &amp; one, T &amp; two) -&gt; 
    zipit&lt;decltype(std::begin(std::declval&lt;T&amp;&gt;()))&gt;
    {
      return { std::begin(one), std::begin(two) };
    }</pre>
	
<h4>dice_game.cpp</h4>

<ul>
	<li>In class <code>randomize</code> the <code>mt19937</code> instance should not be left un-seeded.   Either pass the seed as an argument to the constructor or call <code>mt19937::seed</code> in the <code>randomize</code> constructor, otherwise every time the program is executed the numbers returned by generator will be the same (and therefore the game results will be the same for the same number of games played). I propose two constructors for class <code>randomize</code> â€“ a default constructor which will use a source of entropy (some OS or hardware source, but worst case the current time) to seed, and another constructor that takes the seed as an argument. See below for a sample implementation and later for a discussion on seeding.</li>
	
	<li>In <code>randomize::operator()</code> the use of <code>%6+1</code> to scale the output of <code>mt()</code> may produce a non-uniform distribution. While it is good enough for this use, thereâ€™s a very tiny bias. If <code>mt()</code> were to generate numbers uniformly distributed over the interval [0,7] then taking modulo 6 of these numbers 0 would map to 0, 1=&gt;1, 2=&gt;2, 3=&gt;3, 4=&gt;4, 5=&gt;5, 6=&gt;0, 7=&gt;1, so the probability of getting a 0 or 1 output is twice the probability of the other numbers. In our case, however, <code>mt()</code> will produce numbers in the range 0â€“2<sup>32</sup>-1, so the bias is unnoticeable with a 1.4 * <sup>10-7</sup>% higher probability of output die rolls 1,2,3. Even so, prefer using <code>std::uniform_int_ distribution</code> to change the distribution of the <code>mt19937</code> instance output â€“ it doesnâ€™t have the bias issue and is more descriptive in terms of intent.
	
		<p>The randomize class then would look something like this:</p>
		
		<pre class="programlisting">
    class randomize {
       std::mt19937 rng;
       std::uniform_int_distribution&lt;int&gt; D6;
    public:
       randomize(decltype(rng)::result_type seed)
       : rng(seed), D6(1,6) { }
       randomize ()
       : randomize ( std::random_device()() ) { }
       int operator()() { return D6(rng); }
    };</pre>
	
		<p>It might be an idea to log the seed value generated by <code>std::random_device</code>, in case the program has to be debugged later.</p>
	</li>

	<li>In <code>play(...)</code> the last argument of both <code>std::generate</code> calls should be <code>std::ref(generator)</code>. Since <code>std::generate</code> takes the third argument by copy <code>std::ref</code> should be used to wrap a reference to generator in an <code>std::reference_wrapper</code> instance. As discussed later the random number generator actually produces a deterministic sequence, rather than true unpredictable random numbers. Without the wrapper the first call to <code>std::generate </code>makes a temporary copy of the generator object for use within the function, and all the internal state is copied with it, afterwards in <code>play(...)</code> the internal state of the generator hasnâ€™t changed, so in the second call to <code>std::generate</code> the sequence of numbers is repeated. The result is that both players get the exact same die throws, hence the repeated draws for the headline bug.</li>
	
	<li>In <code>play(...)</code> this is personal choice, but I prefer <code>int total = 0</code> over <code>int total{}</code> as the expected value is clear.</li>
	
	<li>In <code>play(...)</code> the use of an <code>if</code> and then a <code>copysign</code> call is perhaps a little confusing. The intent is to do a three way comparison. While thereâ€™s a proposal for such a feature in C++ <a href="#[1]">[1]</a> it doesnâ€™t currently exist. There are a number of ways to do this but my preferred approach is a ternary conditional expression operator â€“ it is the most expressive, and simple to execute:
	
<pre class="programlisting">
    total += (diff&lt;0) ? -1 : ( (diff==0)? 0 : 1 );</pre>
	
		<p>Here the intent and the result values are explicit (-1,0,1) and appear in order. If <code>diff</code> is more likely to be in one of the states, 0 for example, then the two ternary conditionals could be re-ordered for performance, so the most common case is dealt with first and the second comparison doesnâ€™t have to be executed, but thatâ€™s not the case here.</p>
	</li>
	
	<li><code>copysign</code> is presumably from <span class="filename">math.h</span>, but the header isnâ€™t included, yet this compiles (g++ 7.3), so Iâ€™m not sure where itâ€™s from. Consider using <code>std::copysign</code> and include <code>cmath</code> if <code>copysign</code> must be used. Otherwise Iâ€™d recommend the ternary operator approach.</li>
	
	<li>In <code>play(...)</code> consider replacing the whole <code>for</code> loop over the zip iterator with <code>std::accumulate</code>:
	
<pre class="programlisting">
    auto get_score_from_throws = [](auto p1,
      auto p2)
    {
      auto diff = p1 - p2;
      return (diff&lt;0) ? -1 : ( (diff==0)? 0 : 1 ); 
    };
    total = std::accumulate (
      begin(player1, player2),
      end(player1, player2), 0,
      [&amp;get_score_from_throws](auto sum,
        const auto &amp; it) {
        return sum += 
        get_score_from_throws(it.first,
          it.second);
      }
    );</pre>
	
		<p>or use <code>std::inner_product</code>:</p>
		
<pre class="programlisting">		
      total = std::inner_product (
        std::begin(player1), std::end(player1),
        std::begin(player2), 0, std::plus&lt;&gt;(),
        get_score_from_throws );</pre>
		
		<p><code>The accumulate version uses the zip</code> iterator, and the function name is more self explanatory. The <code>inner_product</code>, while confusingly named, achieves the same thing, and <em>doesnâ€™t even need the zip iterator</em>.</p>
		
		<p>Alternatively <code>std::reduce</code> or <code>std::transform_reduce</code> could be used, but neither libstdc++ (the STL used by g++) <a href="#[2]">[2]</a>, nor libc++ (the STL used by CLang) <a href="#[3]">[3]</a> have yet to support these C++17 features, so I couldnâ€™t produce sample code.</p>
	</li>

	<li>In <code>play(...)</code> consider making the turns argument unsigned instead of <code>int</code>. You cannot play a negative number of games.</li>
	
	<li>In <code>main(...)</code> turns should be bounds checked</li>
</ul>

<p>So that should get the right result with the existing program design, but Iâ€™d make some design changes also.</p>

<ul>
	<li>If a zip iterator is still required consider using <code>Boost. ZipIterator</code> instead â€“ it supports the zipping of more than two iterators and is tested and known to work.</li>
	
	<li><code>zipit::operator==</code> is a potential source of errors. Since there isnâ€™t an explicit comparison operator the inherited one is used. This is typically the correct behaviour, however if the vectors passed to <code>begin(T,T)</code> and <code>end(T,T)</code> are different lengths there will never be a time when the end zipit iterator is reached, since both <code>first</code> and <code>second</code> have to match. Since theyâ€™re incremented together theyâ€™ll never both match when there are different length vectors. Consider tweaking <code>end(T,T)</code> to set <code>.first</code> and <code>.second</code> to the same offset from the beginning of the vectors. The offset should be the length of the shorter vector.</li>
	
	<li>With its current functionality the <code>randomize</code> class isnâ€™t actually needed at all. Assuming no other features are required the following is a drop-in replacement:
	
<pre class="programlisting">
    auto generator = std::bind ( 
    std::uniform_int_distribution&lt;unsigned&gt;(1,6),
      std::mt19937(rng_seed) );</pre>
	  
		<p>For fun, you could also create a loaded die that has double the chance of rolling a six:</p>
		
<pre class="programlisting">		
    auto loadedD6 = std::bind(
      std::discrete_distribution&lt;unsigned&gt;{
        0,1,1,1,1,1,2}, 
      std::mt19937(rng_seed));</pre>
	  
		<p>Of course, for one player to have the advantage youâ€™d need each player to have different dice types.</p>
		
		<p>With respect to seeding â€“ it might be an idea to make the seed a command line argument, so that you can have reproducible results in testing, something along the lines of:</p>
		
<pre class="programlisting">
    void usage(char * execname) { std::cerr &lt;&lt;
      &quot;Usage: &quot; &lt;&lt; execname &lt;&lt;
      &quot;[--seed &lt;unsigned integer&gt;]\n&quot;; }
    int main(int argc, char *argv[]) {
      using namespace std::string_literals;
      using rng_t = std::mt19937;
      rng_t::result_type rng_seed =
        std::random_device()();
      if ( argc == 3 ) {
        if(&quot;--seed&quot;s != argv[1]) {
          usage(argv[0]); return -1;
        }
        // could throw invalid_exception or 
        // out_of_range
        int seed = std::stol(argv[2]);
        if(seed &lt; 0) throw std::out_of_range(
          &quot;Seed value must be a positive&quot;
          &quot; integer&quot;);
        rng_seed = seed;
      }
      else if(argc!=1) {
        usage(argv[0]); return -1;
      }
      std::cout &lt;&lt; &quot;RNG seed = &quot; &lt;&lt;
        rng_seed &lt;&lt; '\n';
      auto D6 = std::bind(
        std::uniform_int_distribution&lt;unsigned&gt;
        (1,6), rng_t(rng_seed));
    ...</pre>
	</li>
	
	<li>Something to consider is whether we actually need to keep the die throws in memory. No game is dependant on the result of any other, so thereâ€™s no need to store the throws or even the score per round. A loop could make die throws, calculating the score and keeping a running score, without any vectors.
		<p>Of course it can be shown that for two N sided fair dice the chance of throwing the same value is 1/N, the chance the first die throws a smaller number is (N-1)/2N, same for the second die. So we could get the game result with the following generator:</p>
<pre class="programlisting">
    const unsigned die_sides = 6;
    auto game_point_generator = std::bind ( \
      std::discrete_distribution&lt;unsigned&gt;{ 1.0, 
    (static_cast&lt;double&gt;(die_sides)-1.0)/2.0, 
    (static_cast&lt;double&gt;(die_sides)-1.0)/2.0 }, \
      std::mt19937(std::random_device()()) \
      );</pre>
	  
		<p>A call to <code>game_point_generator()</code> will generate 0 if the game is a draw, a 1 if player1 wins, and 2 if player 2 wins.</p>
	</li>

	<li>If the die throws do have to be kept in memory then consider a vector of <code>std::pair</code>s to store the results â€“ this way there is no chance of one vector in the zip iterator being smaller than the other. We also don't need the zip iterator then.</li>
	
	<li><code>zipit</code> could be generalised by using a <code>tuple</code> to allow more than two iterators to be zipped; and thereâ€™s no reason for all iterator types to be the same.</li>
	
	<li><code>zipit</code> should consider SFINAE/<code>enable_if</code> to enable the operator overloads based on the type of the zipped iterators.</li>
	
	<li><code>std::iterator_traits&lt;zipit&gt;</code> should be implemented so that <code>zipit</code> can be better integrated into the STL (for example if it happens to model a random access iterator and states so via <code>iterator_traits</code> then <code>std::advance</code> will be optimised).</li>
	
	<li>In the spirit of C++20 <code>zip_it</code> can be implemented with constexpr modifiers.</li>
</ul>

<h4>Points for discussion</h4>

<p><strong>Random number generation</strong></p>

<p>Random number generators fall into two categories â€“ deterministic and non-deterministic. Since CPUs are deterministic state machines they cannot, without special hardware or external input, produce true entropy. â€˜Randomâ€™ numbers are therefore typically produced by pseudo-random algorithms that are actually deterministic. If you know the internal state and the algorithm, you can predict the next number exactly. This is how the <code>rand()</code> library call works (thatâ€™s typically a linear congruential generator <a href="#[4]">[4]</a>), as well as <code>mt19937</code> which is available since C++11. To change the sequence produced every time the program is run it is typical (although perhaps not always correct) to bootstrap the generator from the current time. Since C++11 <code>std::random_device</code> can be used to seed the deterministic generator. <code>std::random_device</code> takes entropy from an implementation dependant source (for example RDRAND on Intel/AMD, or <span class="filename">/dev/urandom</span> under linux â€“ both use external events such as interrupts to accumulate entropy) to try and generate non-deterministic random numbers, but the non-determinism is not guaranteed by <code>std::random_device</code> (26.5.6.2 in <a href="#[5]">[5]</a>).</p>

<p><strong>Creating custom iterators</strong></p>

<p>Weâ€™re not so much creating a custom iterator here, as we are an iterator adaptor. And we also cannot assume the underlying iterator type â€“ it may be a forward input, forward output, bidirectional, or random iterator <a href="#[6]">[6]</a>. And then there are the const and reverse variants. But I think the intention of <code>zipit</code> is still to behave like an STL iterator. One thing is for sure though, writing iterators isnâ€™t easy. Thereâ€™s a fair amount of responsibility that goes into writing one.</p>

<p>If we try to model an input iterator then according to <a href="#[6]">[6]</a> <code>zipit</code> is still missing a post-increment operator and an <code>operator-&gt;</code>. The post-increment operator isnâ€™t that difficult and can be expressed in terms of the pre-increment operator:</p>

<pre class="programlisting">
  zipit operator++(int)
  {
    auto temp = *this;
    ++*this;
    return temp;
  }</pre>
  
<p><code>operator-&gt;</code> makes my head hurt, however. It should allow <code>iter-&gt;member</code> ... but how do we do that while managing two iterators?</p>

<pre class="programlisting">
  zipit&lt;Iter&gt; const * operator-&gt;() const
  {
    return this;
  }</pre>
  
<p>works, but then usage is ugly:</p>

<pre class="programlisting">
  std::vector&lt;std::string&gt; sv1 = {&quot;a&quot;,&quot;b&quot;,&quot;c&quot;};
  std::vector&lt;std::string&gt; sv2 = {&quot;c&quot;,&quot;b&quot;,&quot;a&quot;};
  auto sv_zip = begin(sv1,sv2);
  std::cout &lt;&lt; sv_zip-&gt;first-&gt;length() &lt;&lt; '\n';</pre>
  
<p>and possibly incorrect. Should usage be <code>sv_zip-&gt;first.length()</code>? Or <code>sv_zip.first-&gt;length()</code>? The latter wonâ€™t call <code>operator-&gt;</code> and is available for free as long as the inheritance from <code>std::pair</code> is public.</p>

<p>Alas itâ€™s hard to know what to return from a zip iterator when pointers or references are involved.</p>

<p>If we want to take it further, and model an output iterator then we must make the iterator dereferenceable as an lvalue (i.e. <code>operator*</code> returns a type convertible to <code>T &amp;</code>). This leads to a similar problem.</p>

<p>Bear in mind also that the iterator weâ€™re storing is not necessarily a pointer, itâ€™s something that behaves like a pointer, but may not be a raw pointer. Case in point â€“ <code>vector&lt;bool&gt;::iterator</code> is a proxy class that accesses the underlying storage through something sufficiently advanced (magic?). Dereferencing it returns a <code>vector&lt;bool&gt;::reference</code>.</p>

<p>Using this for inspiration we can make an attempt at <code>operator*</code> for output iterators:</p>

<pre class="programlisting">
  // references cannot be stored in std::pair, 
  // so we create a wrapper
  template &lt;typename T&gt; class ref_wrap {
    private:
      T &amp; p;
    public:
      explicit ref_wrap (T &amp; t) : p{t} {}
      operator T &amp; () const noexcept {
        return p; }
      T &amp; operator= (const T &amp; t) const {
        p = t; return p; }
  };
  // convert the iterator type to a reference 
  // type
  template &lt;typename T&gt; struct
    iter_reference_type { typedef typename
    std::iterator_traits&lt;T&gt;::reference type; };
  template &lt;typename T&gt; struct
    iter_reference_type &lt; T * &gt; {
      typedef T &amp; type; };
  // optionally wrap the reference in our 
  // wrapper
  template &lt;typename T&gt; struct
    wrapped_reference_type { typedef T type; };
  template &lt;typename T&gt; struct
    wrapped_reference_type &lt; T &amp; &gt; { typedef 
      ref_wrap&lt; T &gt; type; };
  template &lt;typename Iter&gt; struct
    wrapped_iter_reference_type {
    typedef typename wrapped_reference_type&lt; \
      typename iter_reference_type&lt;Iter&gt;::type \
      &gt;::type type; };
  // a second template parameter is added to 
  // zipit in case the reference deduction 
  // doesn't work for some custom iterator
  template &lt;typename Iter,
    typename wrapped_reference = typename 
  wrapped_iter_reference_type&lt;Iter&gt;::type &gt;
  class zipit : public std::pair&lt;Iter, Iter&gt;
  {
  ...
  public:
    typedef wrapped_reference reference;
    std::pair&lt;reference, reference&gt; operator*()
      const {
      return std::make_pair(
        reference(*this-&gt;first), 
        reference(*this-&gt;second) );
    }
  ...
  };</pre>
  
<p>Here we have a simple class to wrap a reference, which allows us to store it in an <code>std::pair</code>. <code>std::reference_wrapper</code> cannot be used since it is implicitly convertible from <code>T</code> and any assignment then simply changes the reference, not the referred to value.</p>

<p>The SFINAE is required to extract the true value reference type. <code>T * </code>converts to <code>T &amp;</code>, <code>std::vector&lt;T&gt;::iterator</code> converts to either the proxy object, or if it is a raw pointer to <code>T &amp;</code>. Raw references then get wrapped and packed in a pair. Proxy objects donâ€™t get wrapped, they just get put into a pair.</p>

<p>The same wrapper could be used to implement <code>operator-&gt;</code> but since we have to return a pointer to the <code>std::pair&lt;reference, reference&gt;</code> we might have to allocate the pair object on the heap and return as a <code>unique_ptr</code>. And thatâ€™s really ugly. I want no part of it.</p>

<p>â€¦and of course plenty more features are needed if the iterator is to model one of the other iterator types.</p>

<p>â€¦and donâ€™t forget to specialise <code>std::iterator_traits</code> (deriving from <code>std::iterator</code> was deprecated in C++17).</p>

<p>â€¦and since C++11 the iterators must be swappable through <code>std::swap</code>â€¦ so specialise that too.</p>

<p>All in all, implementing iterators can lead to bouts of anxiety and heavy drinking. So drop <code>zipit</code> from the code â€“ just use <code>Boost.ZipIterator</code> and accept its semantics, or <code>std::inner_product</code> without a zip iterator, or <code>std::vector&lt;std::pair&lt;int,int&gt;&gt;</code>, or donâ€™t store the dice throws.</p>

<h4>References</h4>

<p class="bibliomixed"><a id="[1]"></a>[1]	<a href="http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0515r0.pdf">http://open-std.org/JTC1/SC22/WG21/docs/papers/2017/p0515r0.pdf</a></p>

<p class="bibliomixed"><a id="[2]"></a>[2]	<a href="https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2017">https://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2017</a></p>

<p class="bibliomixed"><a id="[3]"></a>[3]	<a href="http://libcxx.llvm.org/cxx1z_status.html">http://libcxx.llvm.org/cxx1z_status.html</a></p>

<p class="bibliomixed"><a id="[4]"></a>[4]	<a href="https://en.wikipedia.org/wiki/Linear_congruential_generator">https://en.wikipedia.org/wiki/Linear_congruential_generator</a></p>

<p class="bibliomixed"><a id="[5]"></a>[5]	<em>The C++11 Programming Language standard</em> â€“ ISO/IEC 14882:2011(E)</p>

<p class="bibliomixed"><a id="[6]"></a>[6]	<a href="http://www.cplusplus.com/reference/iterator/">http://www.cplusplus.com/reference/iterator/</a></p>

<h3>Balog Pal</h3>

<p>This entry starts with a really good teaser. Dice game that is always drawn? In real life I would ask â€œdid you check your RNG sequence? Iâ€™d bet you either keep generating the same number or the exact same sequence for the two players.â€   Itâ€™s worth a look just to prove my gut right or wrong.</p>

<p>Looking at the code I see some iterator magic that I save for later. Then more magic with the new <code>&lt;random&gt;</code> that Iâ€™m not up to date with. However, in the past I read a lot of problems related to RNG. It reminds me an old story from around the millennium. I had to write an application that used winsock sockets for communication. When it was â€˜readyâ€™ I went to the forums to ask some peersâ€™ opinion. And the people, instead of commenting on the code just pointed me to fetch the â€˜winsock lame listâ€™ and serve myself. As anyone would guess I found a good amount of matchesâ€¦   And <code>random</code> looks like a similar can of worms, maybe someone compiled a similar list? Letâ€™s try a web search for â€˜lame list for rngâ€™. Wow, guess what, first hit is titled â€˜The C++ &lt;random&gt; Lame List â€“ Elbenoâ€™ <a href="#[BP1]">[1]</a>. It even refers to the ws lame list as the muse. Unfortunately, it lacks the explanations but even just the points can help a lot.</p>

<p>Matching the code against the list I see hits on 6, 7, 11, 14 and we get half-dozen good hints on what to avoid as we try to fix. And especially 14 looks like a killer that may match my first clue. But letâ€™s stash that too, and put the code in a compiler so we can instrument it with some output at interesting points. And while at it, try some static analysis.</p>

<p>In Visual Studio 2017 (15.5.5) default W3 compile gives one warning on <code>total +=</code> â€“ conversion <code>double</code> to <code>int</code>. Maybe Wall tells more. Huh, indeed. 900 warnings! Too bad all but 4 come from the standard headers. I wonder if the VS team ever tried the dogfood method that others use to create actually usable stuff. The 3 warnings on our code are <code>int signed/unsigned</code> mismatch that are not very interesting till we not press the bounds. But the <code>int turns</code> that comes directly from user input is just used to size the vectorâ€¦ weâ€™ll try to play with -1 later. &lt;evil grin&gt;</p>

<p>Now letâ€™s see analyze. Weâ€™re warned that <code>begin()</code> and <code>end()</code> can be declared <code>noexcept</code>. Also â€˜The reference argument <code>generator</code> for function <code>play</code> can be marked as constâ€. That in general we treat by adding the <code>const</code>, but for this case it is an indication of a problem: we expect the generator to mutate, if it could be <code>const</code>, we messed up. Must be that missing <code>ref()</code> from point 14.</p>

<p>Lastly, a warning â€œDo not dereference a invalid pointer (lifetimes rule 1). <code>return of +=</code> was invalidated by <code>end of scope for allotemp.2</code>â€ that honestly beats me, especially as <code>op -=</code> has identical code without warning. </p>

<p>Clang invoked through the â€˜clang power toolsâ€™ extension also picked that ref should be <code>const</code> [see the clang-tidy check google-runtime-references] and said that in call <code>play()</code> the first arg is not initialized, what is not really true for our case, if we got there, <code>cin</code> reported okay, so it did complete <code>&gt;&gt;</code> properly.</p>

<p>Letâ€™s just run it as is to see those draws. No luck here, we hit an assert: â€œvector iterator not dereferencableâ€ in <code>operator*</code>, debugger shows <code>this-&gt;first</code> being <code>null</code>. Wow. While at it, I take a peek into the sequences sitting in player 1: 3 1 3 6, and 2: same. Was I right or was I right? But I really want to see the output, maybe in release build that assert will not stand in the way? Indeed, now the program executes, and I get â€¦ â€˜Player 1 winsâ€™ on all my tries. Letâ€™s hope we didnâ€™t also launch some nukes on another continent.</p>

<p>Originally, I did not want to bother with the code before <code>class randomize </code>at all, but must push back the related rant even further, to at least get UB out of the way. We donâ€™t have too much code before the assert, just the <code>begin()</code> so letâ€™s look at that: guess what, it takes out vectors by value, gets the iterator, stores it, then the copies are destroyed for good leaving us with the invalid iterators. Same story with <code>end()</code>. Letâ€™s add the missing <code>&amp;</code>s and see what happens. Yey, no more <code>assert</code>, and weâ€™re finally drawn for all attempts. And if we use <code>std::ref(generator)</code> in the two <code>generate()</code> calls, then we get various results too.</p>

<p>So, once we have the program working as desired, whatâ€™s left besides to throw it ALL away and create properly? From scratch, as we learnt from the food industry, that if you already mixed the bad things with the good, it is hopeless to separate them later, instead we only add what is good. It does not stop us from reusing what we like from the original source be it idea or a code fragment.</p>

<p>For start we paste the original <code>main()</code>. It looks okay-ish for the original aim. We just need a bounds check on <code>turns</code> before passing it on. Call to <code>play()</code> is fine, just make sure <code>generator</code> is passed by ref. And we will need the random source. Having it on the stack will trigger #11. We might ignore that reasoning it is a single case and we are positive to have enough stack space. Or use some alternative, like making it static or have a dynamic instance with <code>make_unique</code>. This program does not want threads, so we can ignore the related points, but commit them to memory.</p>

<p>Now letâ€™s make a proper random source. While at it, letâ€™s also rename it accordingly, <code>random_source</code> is way better description than <code>randomize</code>. The list approves <code>mt19937</code> as a good start, I have to look up how to use it. Along with other hints that weâ€™ll need <code>random_device</code> and <code>uniform_int_distribution</code>. The latter on cppreference.com has the code for our case. All together I came up with this:</p>

<pre class="programlisting">
  class random_source
  {
    static unsigned int get_seed()
    {
      try {
        std::random_device rd;
        return rd();
      }
      catch (std::exception const&amp;)
      {
        return static_cast&lt;unsigned int&gt; (time(
          nullptr));
      }
    }
    std::mt19937 mt{get_seed()};
    std::uniform_int_distribution&lt;&gt; dis{1, 6};
  public:
    int operator()() {
      return static_cast&lt;int&gt;(dis(mt)); }
  };</pre>
  
<p>The description of <code>random_device</code> is pretty vague, most of it is left to the implementation, but it is intended to do the best to summon some entropy. If it canâ€™t and we get the exception the OP should decide what to do, I just dumped in an alternative source that is less lame as the 2nd violin. Time returns unspecified type, but it is numeric and for unsigned anything goes. The other cast in the <code>op()</code> is benign as the number is in the known range. I was thinking to change the return type instead to <code>unsigned</code>, but for the use plain <code>int</code> is the natural thing. Or is it? Maybe <code>byte</code> is more fitting. That can be rearranged later. Moving on to <code>play()</code>.</p>

<p>The aim was to do play N rounds, in each make both player throw dice, decide the round outcome and accumulate the result.  One way to do that is </p>

<pre class="programlisting">
  int turn(random_source &amp;generator)
  // returns score for player 1: -1 0 or +1
  {
  // return sign( generator() - generator() );  
  // too bad no stock sign function....
    auto const d1 = generator();
    auto const d2 = generator();
    return d1 &lt; d2 ? -1 : d1 &gt; d2;
  }
 int game(int turns, random_source &amp;generator) 
  // the difference between player 1 and 2's wins
  {
    int total = 0;
    for (int i = 0; i &lt; turns; ++i)
      total += turn(generator);
    return total;
  }</pre>
  
<p>And in the original <code>play()</code> function we just</p>

<pre class="programlisting">
  auto const total = game(turns, generator);</pre>
  
<p>and print the result. And we are done. For good. No kidding. Fun thing that it now even works with the original <code>main</code> without bound check and prints draw for -1 instead of crash or assert. </p>

<p>Someone may object that we were supposed to criticize or fix <code>zipit</code>â€¦ Were we actually? It breaks one of my fundamental rule for reviews (and dev process): application programmers are forbidden to write blacklisted stuff, that starts with known timewasters like  â€˜logger classâ€™, â€˜string classâ€™ â€˜refcounting pointerâ€™, and also contains â€˜collectionâ€™ and â€˜iteratorâ€™. For the collection I can be convinced in theory if someone has a problem that requires a really new type of collection not covered by either standard or the many libraries we work with. And for iterator if one opens with â€œI have this code full of algorithm use, I needed an iterator for that special collection to drive them.â€ Not the case here. Even for that case Iâ€™d ask whether it is really needed right now or we may wait a little till ranges finally arrive.</p>

<p>If the more advanced version of the program have actual need to keep record of turns, it can be simply done in a <code>pair&lt;int, int&gt;</code> per round, collection of those and running whatever processing with tools that work (WELL!) out of the box. </p>

<p>And those who really need to implement their own, can start with web search for â€˜how to write c++ iteratorâ€™, the first hit <a href="#[BP2]">[2]</a> is more than promising. </p>

<p>An extra stab at header separation: this simple code does not need a header at all, now, or probably ever. But if some parts are extracted, the header shall be self-containing, have all needed <code>#include</code> lines, not rely on the client.</p>

[Web Editor's Note:  Article is continued 
<a href="/index.php/journals/2514" >here</a>.]</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
