Note that there are some explanatory texts on larger screens.

plurals
  1. POsum of square of each elements in the vector using for_each
    text
    copied!<p>As the function accepted by <a href="http://www.cplusplus.com/reference/algorithm/for_each/" rel="noreferrer">for_each</a> take only one parameter (the element of the vector), I have to define a <code>static int sum = 0</code> somewhere so that It can be accessed after calling the for_each . I think this is awkward. Any better way to do this (still use for_each) ?</p> <pre><code>#include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;iostream&gt; using namespace std; static int sum = 0; void add_f(int i ) { sum += i * i; } void test_using_for_each() { int arr[] = {1,2,3,4}; vector&lt;int&gt; a (arr ,arr + sizeof(arr)/sizeof(arr[0])); for_each( a.begin(),a.end(), add_f); cout &lt;&lt; "sum of the square of the element is " &lt;&lt; sum &lt;&lt; endl; } </code></pre> <p>In Ruby, We can do it this way:</p> <pre><code>sum = 0 [1,2,3,4].each { |i| sum += i*i} #local variable can be used in the callback function puts sum #=&gt; 30 </code></pre> <p><strong>Would you please show more examples how <code>for_each</code> is typically used in practical programming (not just print out each element)?</strong> Is it possible use <code>for_each</code> simulate 'programming pattern' like map and inject in Ruby (or map /fold in Haskell).</p> <pre><code>#map in ruby &gt;&gt; [1,2,3,4].map {|i| i*i} =&gt; [1, 4, 9, 16] #inject in ruby [1, 4, 9, 16].inject(0) {|aac ,i| aac +=i} #=&gt; 30 </code></pre> <p>EDIT: Thank you all. I have learned so much from your replies. We have so many ways to do the same single thing in C++ , which makes it a little bit difficult to learn. But it's interesting :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload