Extends unary_function to do sum : for_each « STL Algorithms Non modifying sequence operations « C++






Extends unary_function to do sum

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

class sum : unary_function<int, void> {
public:
  argument_type sum;

  sum() { 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);

  for(unsigned i=0; i < v.size(); ++i)
    cout << v[i] << endl;

  sum s;

  s = for_each(v.begin(), v.end(), sum());
  cout << "sum of v: " << s.sum << endl;

  v[4]= 99;
  s = for_each(v.begin(), v.end(), sum());
  cout << "sum of v is now: " << s.sum;

  return 0;
}
  
    
  








Related examples in the same category

1.Use for_each with predicate
2.Use for_each function to add value for each element
3.Use for_each function to add first element to each element in the list
4.Use for_each function to print all elements in a vector
5.Call custom function in for_each
6.Use custom function and for_each to calculate mean value
7.A function object that computes an integer sum.
8.Extends a unary_function