title: How to accumulate a result using for_each in C++?
body: <p>I'm trying to reproduce what <code>accumulate</code> does using <code>for_each</code>. However I don't understand what is the problem in the <code>for_each</code> version:</p>
  <pre><code>int main() {
      std::function&lt;float(float, int)&gt; func = [](float a, int i) {return a * i; };
      std::vector&lt;int&gt; m{ 1, 2, 3, 4 }; // &lt;-- Multiply: 1*2*3*4 = 24
  
  
      float accumulationUsingAccumulate = 1.0f;
      accumulationUsingAccumulate = accumulate(m.cbegin(), m.cend(), accumulationUsingAccumulate, func);
      std::cout &lt;&lt; &quot;[Accumulate] Result = &quot; &lt;&lt; accumulationUsingAccumulate &lt;&lt; std::endl;
      
  
      float accumulationUsingForEach = 1.0f;
      std::for_each(m.cbegin(), m.cend(), [&amp;accumulationUsingForEach, &amp;m, &amp;func]() {
          accumulationUsingForEach = func(accumulationUsingForEach, *m.cbegin()++);
      });
      std::cout &lt;&lt; &quot;[For Each] Result = &quot; &lt;&lt; accumulationUsingForEach &lt;&lt; std::endl;
  }
  </code></pre>
  <p>Does the outer lambda function in the second version require an argument?</p>
  <p>The following error messages are returned:</p>
  <p><a href="https://i.stack.imgur.com/jkifL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jkifL.png" alt="enter image description here" /></a></p>