Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum of square of each elements in the vector using for_each

As the function accepted by for_each take only one parameter (the element of the vector), I have to define a static int sum = 0 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) ?

#include <algorithm>
#include <vector>
#include <iostream>

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<int> a (arr ,arr + sizeof(arr)/sizeof(arr[0]));

    for_each( a.begin(),a.end(), add_f);
    cout << "sum of the square of the element is  " << sum << endl;
}

In Ruby, We can do it this way:

sum = 0
[1,2,3,4].each { |i| sum += i*i}   #local variable can be used in the callback function
puts sum    #=> 30

Would you please show more examples how for_each is typically used in practical programming (not just print out each element)? Is it possible use for_each simulate 'programming pattern' like map and inject in Ruby (or map /fold in Haskell).

#map in ruby 
>> [1,2,3,4].map  {|i| i*i} 
=> [1, 4, 9, 16]

#inject in ruby 
[1, 4, 9, 16].inject(0)  {|aac ,i| aac +=i}  #=> 30

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 :)

like image 290
pierrotlefou Avatar asked Aug 25 '09 04:08

pierrotlefou


People also ask

How do you find the sum of all the elements in a vector?

Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.

How do you find the sum of a vector in STL?

Approach: Sum can be found with the help of accumulate() function provided in STL. Syntax: accumulate(first_index, last_index, initial value of sum);

How do you sum a vector?

The triangle law of the addition of vectors states that two vectors can be added together by placing them together in such a way that the first vector's head joins the tail of the second vector. Thus, by joining the first vector's tail to the head of the second vector, we can obtain the resultant sum vector.

How do you add elements in the middle of a vector?

Elements can be added in the middle of a Vector by using the java. util. Vector. insertElementAt() method.


2 Answers

No, don't use std::accumulate() use std::inner_product(). No functor required.

#include <vector>
#include <numeric>

void main()
{
    std::vector <int> v1;
    v1.push_back(1);
    v1.push_back(2);
    v1.push_back(3);
    v1.push_back(4);

    int x = std::inner_product( v1.begin(), v1.end(), v1.begin(), 0 );
}
like image 156
mocj Avatar answered Sep 19 '22 20:09

mocj


Use std::accumulate

#include <vector>
#include <numeric>

// functor for getting sum of previous result and square of current element
template<typename T>
struct square
{
    T operator()(const T& Left, const T& Right) const
    {   
        return (Left + Right*Right);
    }
};

void main()
{
    std::vector <int> v1;
    v1.push_back(1);
    v1.push_back(2);
    v1.push_back(3);
    v1.push_back(4);

    int x = std::accumulate( v1.begin(), v1.end(), 0, square<int>() );
    // 0 stands here for initial value to which each element is in turn combined with
    // for our case must be 0.
}

You could emulate std::accumulate as in nice GMan's answer, but I believe that using std::accumulate will make your code more readable, because it was designed for such purposes. You could find more standard algorithms here.

like image 27
Kirill V. Lyadvinsky Avatar answered Sep 20 '22 20:09

Kirill V. Lyadvinsky