// Demonstration of the accumulate algorithm
// (NDE, 2014-01-07)
#include <cstdlib>
#include <ctime>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
double multiply(double x, double y)
{
return x*y;
}
int main()
{
// Seed pseudorandom number generator
srand(time(NULL));
// Populate vector with pseudorandom numbers in range 1-100
vector<double> v;
for (int i = 0; i < 10; ++i) {
double value = static_cast<double>(rand()%100 + 1);
v.push_back(value);
}
// Display vector contents
ostream_iterator<int> out(cout, " ");
copy(v.begin(), v.end(), out);
cout << endl;
// Accumulate sum of vector's values
double sum = accumulate(v.begin(), v.end(), 0.0);
cout << "Sum = " << sum << endl;
// Accumulate product of vector's values
double product = accumulate(v.begin(), v.end(), 1.0, multiply);
cout << "Product = " << product << endl;
return 0;
}