Using function accumulate with a function pointer and with a function object. - C++ STL Algorithm

C++ examples for STL Algorithm:accumulate

Description

Using function accumulate with a function pointer and with a function object.

Demo Code

#include <iostream> 
#include <vector> // vector class-template definition 
#include <algorithm> // copy algorithm 
#include <numeric> // accumulate algorithm 
#include <functional> // binary_function definition 
#include <iterator> // ostream_iterator 
using namespace std; 

int sumSquares( int total, int value ) { 
    return total + value * value; 
}

template< typename T > 
class SumSquaresClass : public binary_function< T, T, T > 
{ 
public: //from   ww w  .  j  av  a2s . c  o  m
    T operator()( const T &total, const T &value ) 
    { 
        return total + value * value; 
    }
};

int main() 
{ 
    const int SIZE = 10; 
    int array[ SIZE ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 
    vector< int > integers( array, array + SIZE ); // copy of array 
    ostream_iterator< int > output( cout, " " ); 
    int result; 

    cout << "vector integers contains:\n"; 
    copy( integers.begin(), integers.end(), output ); 

    result = accumulate( integers.begin(), integers.end(), 0, sumSquares ); 

    cout << "\n\nSum of squares of elements in integers using " << "binary\nfunction sumSquares: " << result; 

    result = accumulate( integers.begin(), integers.end(), 0, SumSquaresClass< int >() ); 

    cout << "\n\nSum of squares of elements in integers using " 
       << "binary\nfunction object of type " 
       << "SumSquaresClass< int >: " << result << endl; 
}

Result


Related Tutorials