Use a function object with for_each() with the summation function object: - C++ STL Algorithm

C++ examples for STL Algorithm:for_each

Description

Use a function object with for_each() with the summation function object:

Demo Code

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;

class summation : unary_function<int, void> {
   public:/*  w  w w.  j av a  2 s. c om*/
   argument_type sum;
   summation() { sum = 0; }


   result_type operator()(argument_type i) {
      sum += i;
   }
};
int main()
{
   vector<int> v;
   for(int i=1; i < 11; i++) v.push_back(i);
   cout << "Contents of v: ";
   for(unsigned i=0; i < v.size(); ++i)
      cout << v[i] << " ";
   cout << "\n";
   // Declare a function object that receives the object
   // returned by for_each().
   summation s;
   s = for_each(v.begin(), v.end(), summation());
   cout << "Summation of v: " << s.sum << endl;
   cout << "Setting v[4] to 99\n";
   v[4]= 99;
   s = for_each(v.begin(), v.end(), summation());
   cout << "Summation of v is now: " << s.sum;
   return 0;
}

Result


Related Tutorials