title: C++ Primer 5th Edition exercise 3.24 - iterators in vectors
body: <p>I just started learning C++ by myself using Lippman, Lajoie &amp; Moo's C++ Primer Fifth Edition (5th printing, may 2014) in september 2014. Some exercises in that book I could do, some I had to look here for help and at this one I'm stuck for days. I searched Google, blogs and other forums and got nothing, so I ask you for help. It is the exercise 3.24 at page 113, which asks the same as the exercise 3.20 in page 105, but using iterators: </p>
  
  <blockquote>
    <p>Read a set of integers into a vector. Print the sum of each pair of adjacent elements. Change your program so that it prints the sum of the first and last elements, followed by the sum of the second and second-to-last, and so on.</p>
  </blockquote>
  
  <p>Using iterators as it asked, I could do the first part:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  using std::cin; using std::cout; using std::endl; using std::vector;
  
  int main()
  {
     vector&lt;int&gt; lista;
     int num_entra = 0;
  
     while (cin &gt;&gt; num_entra)
         lista.push_back(num_entra);
  
  
     cout &lt;&lt; "Sum of adjacent pairs: " &lt;&lt; endl;
     for (auto it = lista.begin(); it != lista.end() - 1; ++it)
     {
         *it += *(it + 1);
         cout &lt;&lt; *it &lt;&lt; ' ';
     }
  
     return 0;
  }
  </code></pre>
  
  <p>The code above works as intended, but the part where I need to sum the first and last, second and second to last... etc. has an issue I just can't solve:</p>
  
  <pre><code>int main()
  {
     vector&lt;int&gt; lista;
     int num_entra = 0;
  
     while (cin &gt;&gt; num_entra)
         lista.push_back(num_entra);
  
  
     auto ult = lista.end();
  
     cout &lt;&lt; "Sum of the first and last elements until the center: " &lt;&lt; endl;
     for (auto it = lista.begin(); it != lista.end() - 1; ++it)
     {
         *it = *it + *(--ult);
         cout &lt;&lt; *it &lt;&lt; ' ';
     }
  
     return 0;
  }
  </code></pre>
  
  <p>If the user enters <code>1 2 3 4 5 6</code>, the program adds 1 + 6, 2 + 5 and 3 + 4 as it should,<br>
  but then it adds the last result (7) with 5 and then with 6 and I can't seem to find a way to stop this behavior. What can I do so the program shows only one sum for each pair until the center of the list?
  Thank you in advance.</p>