    <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 105</title>
        <link>https://members.accu.org/index.php/articles/2372</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">Programming Topics + CVu Journal Vol 29, #2 - May 2017</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>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</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/c373/">292</a>
<br />

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

                    -                        <a href="https://members.accu.org/index.php/articles/c65+373/">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 105</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 03 May 2017 09:23:32 +01:00 or Wed, 03 May 2017 09:23:32 +01: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 class="blockquote">I was trying to write a simple template that gets the unique values from a range of values (rather like the Unix program uniq) but my simple test program throws up a problem.</p>

<pre class="programlisting">
    test with strings
    a a b b c c =&gt; a b c
    test with ints
    1 1 2 2 3 3 =&gt; 1 1 2 3</pre>
	
<p class="blockquote">Why is the duplicate 1 not being removed?</p>

<p>The code is in Listing 1 (unique.h) and Listing 2 (unique.cpp).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &lt;iterator&gt;
#include &lt;vector&gt;
// get unique values in the range [one, two)
template &lt;typename iterator&gt;
std::vector&lt;typename iterator::value_type&gt;
unique(iterator one, iterator two)
{
  if (distance(one, two) &lt; 2)
  {
    // no duplicates
    return {one, two};
  }
  // first one can't be a duplicate
  std::vector&lt;typename iterator::value_type&gt;
  result{1, *one};
  while (++one != two)
  {
    auto next = *one;
    bool is_unique =
     (*result.rbegin() != next);
    if (is_unique)
    {
       result.push_back(next);
    }
  }
  return result;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;vector&gt;
#include &quot;unique.h&quot;
template &lt;typename T&gt;
void test(std::ostream &amp;os,
  std::vector&lt;T&gt; const &amp;vector)
{
   auto result =
     unique(vector.begin(), vector.end());
   auto out =
     std::ostream_iterator&lt;T&gt;(os, &quot; &quot;);
   copy(vector.begin(), vector.end(), out);
   os &lt;&lt; &quot;=&gt; &quot;;
   copy(result.begin(), result.end(), out);
   os &lt;&lt; &quot;\n&quot;;
}
int main()
{
   std::cout &lt;&lt; &quot;test with strings\n&quot;;
   std::vector&lt;std::string&gt; ptrs;
   ptrs.push_back(&quot;a&quot;);
   ptrs.push_back(&quot;a&quot;);
   ptrs.push_back(&quot;b&quot;);
   ptrs.push_back(&quot;b&quot;);
   ptrs.push_back(&quot;c&quot;);
   ptrs.push_back(&quot;c&quot;);
   test(std::cout, ptrs);
   
   std::cout &lt;&lt; &quot;test with ints\n&quot;;
   std::vector&lt;int&gt; ints;
   ints.push_back(1);
   ints.push_back(1);
   ints.push_back(2);
   ints.push_back(2);
   ints.push_back(3);
   ints.push_back(3);
   test(std::cout, ints);
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<h2>Critique</h2>

<h3>Jon Summers</h3>

<p>Header file <span class="filename">unique.h</span> initialises the result vector in this statement:</p>

<pre class="programlisting">
  std::vector&lt;typename iterator::value_type&gt;
  result{ 1, *one };</pre>
  
<p>The initial values are passed in an initialiser list. Unfortunately, at least for this question, the initialiser list passed to a vector can have two meanings. The data can either be a list of values, each having the same type; or an integer that specifies the initial size, followed by data either of the same or a different type.</p>

<p>The data type of <code>*one</code> is templatised. When instantiated with a <code>std::string</code>, the initialiser list is</p>

<pre class="programlisting">CodeListing&gt;
  { 1, std::string (&quot;some string&quot;) }</pre>
  
<p>The compiler understands that to mean: â€œCreate a vector having one element, whose value is â€˜stringâ€™â€.</p>

<p>When instantiated with an <code>int</code>, the initialiser list is </p>

<pre class="programlisting">
  { 1, 1 }</pre>
  
<p>The compiler understands that to mean: â€œCreate a vector having two elements, whose values are 1 and 1.â€</p>

<p>The following loop that examines successive values for uniqueness doesnâ€™t see the first element in the <code>vector&lt;int&gt;</code>, because its logic assumes an initial length of 1.</p>

<h3>Paul Floyd</h3>

<p>My first reactions on reading the code were</p>

<ul>
	<li>why is this reinventing the wheel when <code>std::unique</code> exists? (<a href="http://en.cppreference.com/w/cpp/algorithm/unique">http://en.cppreference.com/w/cpp/algorithm/unique</a>)</li>
	<li>which constructor is being called for â€˜<code>result</code>â€™ in â€˜<code>unique</code>â€™?</li>
</ul>

<p>The compiler [clang++ on Mac OS] also isnâ€™t too happy with this re-inventing of the wheel:</p>

<pre class="programlisting">
  cc104.cpp:10:6: error: call to 'unique' is 
  ambiguous
    unique(vector.begin(), vector.end());</pre>
	
<p>In order for it to compile, I had to rename â€˜<code>unique</code>â€™.</p>

<p>The behaviour of this unique is different to that of <code>std::unique</code>. The version presented here copies unique elements to a new vector (without any call to reserve). It then returns this vector, which may require another copy operation â€“ â€˜<code>unique</code>â€™ has more than one return path which may inhibit NRVO. <code>std::unique</code> modifies the container, moving unique elements towards the head. This minimizes the amount of allocation and copying, and still allows the user to make a copy if she doesnâ€™t want the original vector to be modified. Personally I prefer <code>std::unique</code> as it is more in the C++ philosophy that it doesnâ€™t make you pay for something that you donâ€™t necessarily want.</p>

<p>As to which constructor is being called for <code>result</code> in <code>unique</code>, letâ€™s look at the code:</p>

<pre class="programlisting">
  result{1, *one};</pre>

<p>Unfortunately, this could have two meanings. If the type of <code>*one</code> is the same as <code>1</code>, i.e., an <code>int</code>, then this can be a <code>std::initializer_list</code>, corresponding to the following vector constructor:</p>

<pre class="programlisting">
  vector(std::initializer_list&lt;T&gt; init, 
    const Allocator&amp; alloc = Allocator());
<p>If the type of <code>*one</code> isnâ€™t <code>int</code>, then the constructor is</p>
  vector(size_type count, 
    const T&amp; value,
    const Allocator&amp; alloc = Allocator());</pre>
	
<p>The second case occurs when the vector is instantiated with <code>std::string</code>, consequently <code>result</code> contains a single value, the first value of referenced by the input iterator <code>one</code>. This is probably the intent of the code.</p>

<p>The first case occurs when the vector is instantiated with <code>int</code>. In this case, the first <code>1</code> isnâ€™t considered to be the count, it is treated as a value in the init list. By coincidence it happens to be the same as the input vector values. So it isnâ€™t the case that the first <code>1</code> isnâ€™t being removed, rather an extra <code>1</code> is always being inserted at the head position.</p>

<p>To wrap up, I have a few nits. I donâ€™t like the arguments called <code>vector</code> and <code>iterator</code>. In fact I donâ€™t like any language keywords or standard library names to be used as variable names. This just makes the code harder to read and more difficult to talk about.</p>

<p>Lastly, the <code>std::vector</code>s in <code>main</code> could be more concisely initialized with init lists.</p>

<h3>Raimondo Sarich</h3>

<p>Firstly, I could not compile the code with â€œ<code>error: call to 'unique' is ambiguous</code>â€. I renamed the function to <code>myunique</code>, I assume the developer is using a more permissive compiler.</p>

<p>The bug is pretty easy to spot, this:</p>

<pre class="programlisting">
  std::vector&lt;typename iterator::value_type&gt;
  result{1, *one};</pre>
  
<p>has to change to this:</p>

<pre class="programlisting">
  std::vector&lt;typename iterator::value_type&gt; 
  result(1, *one);</pre>
  
<p>This problem is covered Scott Meyersâ€™ <em>Effective Modern C++</em>, Item 7:</p>

<p class="blockquote">If, however, one or more constructors declare a parameter of type <code>std::initalizer_list</code>, calls using the braced initialization syntax strongly prefer the overloads taking <code>std:initalizer_lists</code>. Strongly. If thereâ€™s any way for compilers to construe a call using a braced initializer to be a constructor taking a <code>std::initalizer_list</code>, compilers will employ that interpretation.</p>

<p>He goes on to explain exactly this difference between constructing a <code>std::vector</code> of numeric types with curly braces versus parentheses. Beware <code>std::vector</code>!</p>

<p>There seems to be little else to remark on. The code could use braced initialization of the test vectors, a scattering of <code>const</code> (the vectors, <code>two</code>, <code>next</code>, and <code>is_unique</code>), and <code>cbegin</code>/<code>cend</code>.</p>

<p><code>std::vector::back()</code> would be better than <code>*std::vector::rbegin()</code>. And of course, <code>std::unique</code> should be preferred outside academic purposes.</p>

<h3>James Holland</h3>

<p>At first glance, the result of the studentâ€™s program seems baffling. How can the software produce two different results just because on one occasion the vector contains elements of type <code>int</code> and on another occasion elements of type <code>std::string</code>? The reason for this behaviour hinges on the set of constructors <code>std::vector</code> possesses and the way a particular constructor is selected.</p>

<p>Consider what happens when the compiler comes across the statement <code>std::vector&lt;std::string&gt; result{1, &quot;a&quot;}</code>, for example. The compiler tries to match the parameter types to one of <code>std::vector</code>â€™s constructors. The compilerâ€™s first choice is to select the constructor with a parameter type of <code>std::initializer_list&lt;T&gt;</code>. This is feasible as the vectorâ€™s definition used braces in the initialisation. However, the compiler cannot use this constructor as the first value in the initialisation list is not convertible to a string. The compiler has to discard the constructor and attempt to select another. Eventually the compiler comes across a constructor that takes a numerical value and an <code>std::string</code>. The compiler will use this constructor to create an <code>std::vector</code> containing, in this case, one string of value <code>&quot;a&quot;</code>.</p>

<p>Now, consider what happens when the definition is changed to <code>std::vector&lt;int&gt; result{1, 1}</code>. As brace initialisation is used, the compiler first considers a constructor with <code>std::initializer_list&lt;T&gt;</code> as a parameter type, as before. This time the compiler does not reject the constructor as all the braced initialisation values are of type <code>int</code> (the type specified in the angle brackets of the definition). In this case the selected constructor creates an <code>std::vector</code> with two elements, both of value 1.</p>

<p>What we have seen is that similar looking definitions can initialise vectors with a varying number of elements. This behaviour is regrettable and probably represents a flaw in the design of <code>std::vector</code>. It is this problem that the student has unwittingly encountered.</p>

<p> The troublesome statement in the studentâ€™s code is just after the comment &quot;<code>// first one can't be a duplicate</code>&quot;. Using parenthesises instead of braces will result in the appropriate constructor being called and will provide the required initialisation. The studentâ€™s program will now work as expected.</p>

<p>When designing code to fulfil some requirement, it is always beneficial to see if library functions can be used in 
place of writing code from scratch.  In the studentâ€™s code, <code>unique()</code> contains two <code>if</code> statements and a <code>while</code> loop and is quite difficult to understand and reason about. I suggest it is possible to use functions from the standard library to perform the same function while being simpler to understand. Using such library functions will go a long way in ensuring the software performs as required. I offer the code below as a directreplacement for the studentâ€™s <code>unique()</code> function. </p>

<pre class="programlisting">
  template &lt;typename iterator&gt;
  std::vector&lt;typename iterator::value_type&gt;
  unique(iterator one, iterator two)
  {
    std::vector&lt;typename iterator::value_type&gt;
      result{one, two};
    const auto end = std::unique(result.begin(),
      result.end());
    result.resize(std::distance(result.begin(),
      end));
    return result;
  }</pre>
  
<p>The body of the replacement function has only three statements of any significance. The first creates a vector containing the range of values, the second moves any adjacent duplicates to the end of the vector and the fourth reduces the size of the vector by discarding the duplicate values. Finally, the function returns the processed vector. </p>

<h3>Robert Lytton</h3>

<p>Elizabeth Barrett Browning once said of C++, â€œHow do I construct thee? Let me count the waysâ€, and let us follow her lead with a class <code>T</code>.</p>

<pre class="programlisting">
  T t1; T t2(t1); T t3=t1; T t4(1,2,3);
  T t5{}; T t6{t1}; T t7={t1}; T t8{1,2,3};
  T t9={1,2,3};</pre>
  
<p>As an aside, <code>T</code>â€™s implementation uses the non-rule â€œrule of zeroâ€, outsourcing ownership to smart pointers, thus the compiler produces just what we need, including rvalue constructors such as:</p>

<p>  <code>T t2b(returnsT());</code></p>

<p>Phew!</p>

<p>Regarding all this construction Liz may â€œlove thee to the depth and breadth and heightâ€ but I am not so sure. It seems less â€œsmilesâ€ and more â€œtears, of all my lifeâ€.</p>

<p>So â€œas men strive for rightâ€ canâ€™t we cut through all of this for one true construction syntax and forget about the rest?</p>

<p>The brace constructor syntax arrived in C++11 and at first glance looks like a uniform initializing syntax, with benefits. As intimated above, all we need to do is replace the parentheses with braces and get a few bonus constructs for free viz:</p>

<ul>
	<li><code>T t{};</code> is not a function declaration but constructs an object.</li>
	<li><code>class T { int i{0}; }</code> is an alternative to using a member initializer list.</li>
</ul>

<p>We can also construct containers more elegantly.</p>

<p>For example, in the exercise <code>main()</code> function, the container initialisation:</p>

<pre class="programlisting">
  std::vector&lt;std::string&gt; ptrs;
  ptrs.push_back(&quot;a&quot;);
  ptrs.push_back(&quot;a&quot;);
  ptrs.push_back(&quot;b&quot;);
  ...</pre>
  
<p>can use an <code>initializer_list</code> as the constructor argument:</p>

<pre class="programlisting">
  std::vector&lt;std::string&gt; ptrs {&quot;a&quot;,&quot;a&quot;,&quot;b&quot;,...</pre>
  
<p>Hang on, what does â€œ<code>initializer_list</code> as the constructor argumentâ€ mean?</p>

<p>Ah, yes. A class may declare a <code>T(std::initializer_list&lt;U&gt;)</code> constructor along side its other constructors. Ay, thereâ€™s the rub - the compiler will do all it can to use the <code>initializer_list</code> constructor, even if it needs to convert types to make it fit and one of the other constructors is an exact fit.</p>

<p>For example, in the exercise <code>unique()</code> function, the vector <code>result</code> is constructed using the literal integer <code>1</code> and a value of type â€˜dereferenced iteratorâ€™ inside of braces:</p>

<pre class="programlisting">
  std::vector&lt;typename iterator::value_type&gt;
    result{1, *one};</pre>
	
<p>In the first test:</p>

<ul>
	<li>the dereferenced iterator is of type <code>std::string</code>;</li>
	
	<li>the compiler canâ€™t convert an integer to a string nor a string to an integer;</li>
	
	<li>thus it canâ€™t create an <code>initializer_list</code>;</li>
	
	<li>thus it canâ€™t call the vectorâ€™s <code>initializer_list</code> constructor;</li>
	
	<li>instead it calls the <code>vector(size_type, const T&amp;)</code> constructor.</li>
</ul>

<p>In the second test:</p>

<ul>
	<li>the dereferenced iterator is of type <code>int</code>;</li>
	<li>the compiler can create an <code>std::initializer_list&lt;int&gt;</code>;</li>
	<li>it can call the vectorâ€™s <code>initializer_list</code> constructor;</li>
	<li>thus â€˜resultâ€™ is initialized with two values <code>{1,1}</code>.</li>
</ul>

<p>Hence the output when the test is run.</p>

<p>Changing from braces to parentheses force the compiler to use <code>vector(size_type,const T&amp;)</code> viz:</p>

<pre class="programlisting">
  std::vector&lt;typename iterator::value_type&gt; 
    result(1, *one);</pre>
	
<p>As <code>auto</code> with braces prefers <code>std::initializer_list&lt;&gt;</code> too (unless itâ€™s a return or lambda type or ...) but templates donâ€™t, it seems a uniform initializing syntax is out of reach. I have to be content with, as Liz puts it, â€œif God choose, I shall but construct thee better after this.â€ </p>

<h3>Herman Pijl</h3>

<p>To start with, I donâ€™t like the name <code>iterator</code> as a name for a template parameter type. The template parameter type should use a naming convention, indicating which iterator category (e.g. <code>std::input_iterator_tag</code>) is expected by the template algorithm. Concretely, I would like to see something like</p>

<pre class="programlisting">
  template&lt;typename In&gt;</pre>
  
<p>I would even suggest to use a <code>static_assert</code> at the beginning of the template function definition. When the <code>static_assert</code> fails, a descriptive string would explain that assumption about the iterator category is not met, e.g.</p>

<pre class="programlisting">
  {
    static_assert(std::is_base_of&lt;
      std::input_iterator_tag,
      typename std::iterator_traits&lt;In&gt;::
        iterator_category&gt;(),
      &quot;iterator category must be (derived from)&quot;
      &quot; std::input_iterator_tag&quot;);
    ...
  }</pre>
  
<p>I like this â€˜conceptâ€™ ;-).</p>

<p>The second problem I see in the template declaration is the use of <code>iterator::value_type</code>. This assumes that the iterator is a â€˜complexâ€™ type, i.e. some struct or class. In other words, the iterator cannot be a simple (plain old Kernighan and Ritchie) pointer. I would like to call the template with â€˜legacyâ€™ code</p>

<pre class="programlisting">
  int intArray[] = {1, 1, 2, 3};
  auto result = unique(intArray + 0,
    intArray + sizeof(intArray)/sizeof(int));</pre>
	
<p>In order to achieve this, replace</p>

<pre class="programlisting">
  typename iterator::value_type</pre>
  
<p>by</p>

<pre class="programlisting">
  typename std::iterator_traits&lt;In&gt;::value_type</pre>
  
<p>It looks like <code>std::iterator</code> is deprecated in C++17, so get used to the <code>std::iterator_traits</code> instead.</p>

<h4>Some comments about the template definition</h4>

<p>The implementation starts with an attempt to find out the size of the iterator range. It is clear that if the range contains 0 or 1 element, then there can be no duplicates. Unfortunately, the <code>distance</code> algorithm is a serious overhead. I would guess that the standard implementation of â€˜distanceâ€™ will use the <code>iterator_traits</code> to have an almost immediate answer for random access iterators, but for the other categories, the overhead is enormous.</p>

<p>The intention was clearly to have a (premature) optimisation for small collections, more in particular the empty collection and the singleton collection, but trying to find the size of the iterator range by entirely traversing the range is far from optimal.</p>

<p>Traversing the whole iterator range becomes a disaster when the iterators are traversing an input stream. As the iterators are incremented, the input stream is effectively consumed!</p>

<pre class="programlisting">
  std::istringstream is(&quot;1 1 2 2 3 3&quot;);
  std::istream_iterator&lt;int&gt; isit(is), isend;
  auto result = unique(isit, isend);</pre>
  
<p>After the call to the <code>distance</code> template, the <code>while</code>-loop will not even be entered!</p>

<p>More critique to come.</p>

<p>When the <code>(distance &lt; 2)</code> condition is met, the template function returns a braced initialiser. As the initialiser doesnâ€™t fit the <code>std::initializer_list&lt;T&gt;</code> constructor, the compiler tries to find some non-explicit constructors that fit and it finds a template constructor. Personally I (still) prefer to use the traditional constructor instead of an inialiser because I want to keep control. I only use the curly braces for default construction or when I want to the construct the object with the <code>std::initializer_list&lt;T&gt;</code> constructor.</p>

<pre class="programlisting">
  return std::vector&lt;typename 
    std::iterator_traits &lt;In&gt;::value_type&gt;(
      one, two);</pre>
	  
<p>As the vector has move semantics there is no overhead. You only have to type some more characters.</p>

<p>Now we arrive at the bug.</p>

<pre class="programlisting">
  std::vector&lt;typename In::value_type&gt;
  result {1, *one};</pre>
  
<p>When the value type is <code>int</code>, the initialiser (curly braces) syntax causes the compiler to find two potential constructors</p>

<ul>
	<li><pre class="programlisting">
	  vector(size_type, const T&amp; value,
        const Allocator&amp;alloc = Allocator());
        // not explicit since C++11</pre></li>

	<li><pre class="programlisting">
	  vector(initializer_list&lt;T&gt; init,
        const Allocator&amp;alloc = Allocator());</pre></li>
</ul>

<p>And the Standard says that the winner is: the <code>initializer_list</code>! Unfortunately this was not the one that we wanted. You can solve the ambiguity by using the parentheses instead of the curly braces.</p>

<pre class="programlisting">
  std::vector&lt;typename In::value_type&gt;
  result (1, *one);</pre>
  
<p>When the value type is string, there is only one constructor to consider.</p>


<p>At first sight I liked the trick to find the previous element</p>

<pre class="programlisting">
  *result.rbegin()</pre>
  
<p>but when looking closer to the vector template there exists a back member function.</p>

<pre class="programlisting">
  result.back()</pre>
  
<p>could be slightly more performant.</p>

<p>I made another version <code>my_unique</code> that should do the trick. I experimented a bit with a binary predicate.</p>

<pre class="programlisting">
  #include &lt;iterator&gt;
  #include &lt;vector&gt;
  //extra
  #include &lt;iostream&gt;
  #include &lt;string&gt;
  #include &lt;sstream&gt;
  #include &lt;type_traits&gt;
  #include &lt;functional&gt;
  template&lt;typename In&gt; std::vector&lt;
    typename In::value_type&gt;
    unique(In one, In two)
  {
    // concept
    static_assert(std::is_base_of&lt;
      std::input_iterator_tag,
      typename std::iterator_traits&lt;In&gt;
                  ::iterator_category&gt;(),
      &quot;iterator category must be (derived&quot;
      &quot; from) std::input_iterator_tag&quot;);
    if (std::distance(one,two) &lt; 2)
    {
      return std::vector&lt;
        typename In::value_type&gt;(one, two);
        //return {one, two};
    }
    std::vector&lt;typename In::value_type&gt;
      result (1, *one);
    while(++one != two)
    {
      auto next = *one;
      bool is_unique =
        (*result.rbegin() != next);
      if (is_unique){
        result.push_back(next);
      }
    }
    return result;
  }

  //template&lt;typename In, typename BinPred = 
  //std::not_equal_to&lt;typename In::value_type&gt;&gt;
  template&lt;typename In&gt;
  std::vector&lt;typename 
    std::iterator_traits&lt;In&gt;::value_type&gt;
  my_unique(In one,
    In two,
    std::function&lt;bool(typename 
      std::iterator_traits&lt;In&gt;::value_type
        const &amp;,
      typename
       std::iterator_traits&lt;In&gt;::value_type
         const &amp;)&gt; binPred =
    std::not_equal_to&lt;typename 
      std::iterator_traits&lt;In&gt;::value_type&gt;{})
  {
    static_assert(std::is_base_of&lt;
      std::input_iterator_tag,
      typename std::iterator_traits&lt;In&gt;:: 
        iterator_category&gt;(),
      &quot;iterator category must be (derived from)&quot;
      &quot; std::input_iterator_tag&quot;);
    std::vector&lt;typename
      std::iterator_traits&lt;In&gt;::value_type&gt;
    result;
    if (one != two)
    {
      result.push_back(*one);
      while (++one != two){
        if(binPred(*one ,result.back())){
          result.push_back(*one);
      }
      }
    }
    // post condition: one == two
    return result;
  }
  template&lt;typename In&gt;
  void test(std::ostream &amp;os, In one, In two)
  {
    auto result = my_unique(one, two);
    auto out = std::ostream_iterator&lt;typename 
      std::iterator_traits&lt;In&gt;::value_type&gt;(
        os, &quot; &quot;);
    std::copy(one, two, out);
    os &lt;&lt; &quot;=&gt; &quot;;
    std::copy(result.begin(),
      result.end(), out);
    os &lt;&lt; &quot;\n&quot;;
  }
  template&lt;typename T&gt;
  void test(std::ostream &amp;os,
    std::vector&lt;T&gt; const &amp;vec)
  {
    test(os, vec.begin(), vec.end());
  }
  int main()
  {
    std::vector&lt;std::string&gt; strPtrs
    {&quot;a&quot;, &quot;a&quot;, &quot;b&quot;, &quot;b&quot;, &quot;c&quot;, &quot;c&quot;};
    test(std::cout, strPtrs);
    std::vector&lt;int&gt; intPtrs{1, 1, 2, 2, 3, 3};
    test(std::cout, intPtrs);
    int intArray[] = {1, 1, 2, 3};
    std::cout &lt;&lt; &quot;intArray &quot;;
    test(std::cout, intArray + 0,
      intArray + sizeof(intArray)/sizeof(int));
    // auto resultForArray = my_unique(intArray
    // + 0, intArray +
    // sizeof(intArray)/sizeof(int)
    std::istringstream is(&quot;1 1 2 2 3 3&quot;);
    std::istream_iterator&lt;int&gt; isit(is), isend;
    auto result = my_unique(isit, isend);
    std::copy(result.cbegin(),
      result.cend(),
      std::ostream_iterator&lt;int&gt;(std::cout,
        &quot; &quot;));
    std::cout &lt;&lt; '\n';
    std::vector&lt;int&gt; intPtrsOrig
    {1, 1, 2, 2, 3, 3};
    auto resultOrig = 
      unique(intPtrsOrig.begin(), 
        intPtrsOrig.end());
    std::copy(resultOrig.cbegin(),
      resultOrig.cend(),
      std::ostream_iterator&lt;int&gt;(std::cout,
        &quot; &quot;));
    std::cout &lt;&lt; '\n';
  }</pre>
  
<h2>Commentary</h2>

<p>This is, as a couple of people noted, a fairly straightforward critique with one main point - the troublesome construction of <code>std::vector</code> when used with braced initialisers.</p>

<p>The subsidiary point, which was about preferring the standard library over hand-written code, was slightly overtaken by events for those whose compilers detected the ambiguous overload with <code>std::unique</code> for them. (This occurs when some of the contents of <code>&lt;algorithm&gt;</code> are included indirectly by one of the headers explicitly listed.)</p>

<p>My own replacement for the hand-written <code>unique</code> was:</p>

<pre class="programlisting">
  std::vector&lt;T&gt; result;
  std::unique_copy(one, two,
    std::back_inserter(result));
  return result;</pre>
  
<p>In production code which approach one might take would depend on the precise context.</p>

<p>I was a little surprised that no-one commented on this line:</p>

<pre class="programlisting">
  auto next = *one;</pre>
  
<p>as this takes an unnecessary copy of the object: I would prefer to see <code>auto const &amp;</code> used here. Somehow poor use of <code>auto</code> seems be easy to overlook. </p>

<p>Additionally, I dislike the use of the names <code>one</code> and <code>two</code> - it would be clearer, I feel, to follow the naming convention for algorithms in the standard library and name them <code>first</code> and <code>last</code>.</p>

<p>Finally I would like to expand on Robertâ€™s closing remark about the interaction of <code>auto</code> and <code>initializer_list</code>. The following simple program demonstrates the issue:</p>

<pre class="programlisting">
  #include &lt;initializer_list&gt;
  int main()
  {
    auto i{1};
    return i; // Is this valid?

  }</pre>
  
<p>In the published wording for C++11 and C++14, <code>i</code> is deduced as a variable of type <code>std::initializer_list&lt;int&gt;</code> and so the <code>return</code> statement is invalid.</p>

<p>The good news is that this behaviour has been changed: the relevant paper N3922 was voted into the C++17 working paper in Urbana-Champaign in Nov 2014. With this change, <code>i</code> is now deduced as <code>int</code>. Even better, it was decided to treat the resolution as a <strong>defect</strong> for previous versions of C++.</p>

<p>So this example already compiles successfully with g++ 5.1, clang 3.8 and Visual Studio 2015.</p>

<h2>The Winner of CC 104</h2>

<p>I was pleased to see all five entrants found the problem and were all able to explain, with more or less detail, what it was and how to fix it. Raiâ€™s reference to Scott Meyers was helpful for any who wish to read further.</p>
<p>Several people commented that it would be preferable to make use of the standard library; it is a good habit to get into, when you are needing a fairly standard algorithm, to start by searching the standard library to see if it has already been written! </p>

<p>Herman pointed out a couple of places where the existing code was insufficiently general; input iterators can cause particular problems to generic algorithms (this surfaced recently in the discussions over the changes that were necessary when adding parallel versions of various algorithms into C++17).</p>

<p>Overall though I think Rai picked up the largest number of incidental improvements and so I have awarded him this issueâ€™s prize.</p>

<p> iterators with pointers was valid and did have the side-effect of removing the undefined behaviour. I did like his introduction of a simple helper struct <code>NameScoreEntry</code> to assist with reading the data in: it is very easy to create such structs in C++ and there can be significant benefits for readability with having named fields.</p>

<p>Overall, I think James provided the best critique, so I have awarded him the prize.</p>

<h2>Code Critique 105</h2>

<h3>(Submissions to scc@accu.org by Jun 1st)</h3>

<p class="blockquote">I was writing a simple program to analyse the programming languages known by our team. In code review I was instructed to change languages() method in the programmer class to return a const reference for performance. However, when I tried this the code broke. Iâ€™ve simplified the code as much as I can: can you help me understand whatâ€™s wrong? It compiles without warnings with both MSVC 2015 and gcc 6. I am expecting the same output from both â€˜Original wayâ€™ and â€˜New wayâ€™ but I get nothing printed when using the new way.</p>

<p>The listings are as follows:</p>

<ul>
	<li>Listing 3 is <span class="filename">programmer.h</span></li>
	<li>Listing 4 is <span class="filename">team.h</span></li>
	<li>Listing 5 is <span class="filename">team_test.cpp</span></li>
</ul>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#pragma once

class programmer
{
public:
  // Add a language
  void add_language(std::string s)
  { languages_.push_back(s); }

  // the programmer's languages - original
  std::vector&lt;std::string&gt;
  original() const
  {
    return {languages_.begin(),
            languages_.end()};
  }

  // new - avoid copying for performance
  std::list&lt;std::string&gt; const &amp;
  languages() const
  { return languages_; }

  programmer() = default;

  programmer(programmer const&amp; rhs)
  : languages_(rhs.languages_) {}

  programmer(programmer &amp;&amp;tmp)
  : languages_(std::move(tmp.languages_)) {}

  ~programmer() { languages_.clear(); }
private:
  std::list&lt;std::string&gt; languages_;
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#pragma once

#include &lt;map&gt;

class team
{
public:
  // Add someone to the team
  void add(std::string const &amp;name,
    programmer const &amp; details)
  {
    team_.emplace(
      std::make_pair(name, details));
  }

  // Get a team member's details
  auto get(std::string const &amp;name) const
  {
    auto it = team_.find(name);
    if (it == team_.end())
      throw std::runtime_error(&quot;not found&quot;);
    return it-&gt;second;
  }

private:
  std::map&lt;std::string, programmer&gt; team_;
};
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &lt;iostream&gt;
#include &lt;list&gt;
#include &lt;map&gt;
#include &lt;string&gt;
#include &lt;vector&gt;

#include &quot;programmer.h&quot;
#include &quot;team.h&quot;

int main()
{
  team t;
  programmer p;
  p.add_language(&quot;C++&quot;);
  p.add_language(&quot;Java&quot;);
  p.add_language(&quot;C#&quot;);
  p.add_language(&quot;Cobol&quot;);
  t.add(&quot;Roger&quot;, std::move(p));

  p.add_language(&quot;javascript&quot;);
  t.add(&quot;John&quot;, std::move(p));

  std::cout &lt;&lt; &quot;Original way:\n&quot;;
  for (auto lang : t.get(&quot;Roger&quot;).original())
  {
    std::cout &lt;&lt; lang &lt;&lt; '\n';
  }

  std::cout &lt;&lt; &quot;\nNew way:\n&quot;;
  for (auto lang : t.get(&quot;Roger&quot;).languages())
  {
    std::cout &lt;&lt; lang &lt;&lt; '\n';
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 5</td>
	</tr>
</table>

<p>You can also get the current problem from the accu-general mail list (next entry is posted around the last issueâ€™s deadline) or from the ACCU website (<a href="http://accu.org/index.php/journal">http://accu.org/index.php/journal</a>). This particularly helps overseas members who typically get the magazine much later than members in the UK and Europe.</p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
