#include <numeric> // Accumulate
#include <vector> // Vector
using namespace std;
int main()
{
vector<int> nums{1,2,3,4,5};
int sum = 0;
sum = accumulate(nums.begin(), nums.end(), sum);
// nums.begin() -> first number in a list
// nums.end() -> last number in a list
// sum -> starting value before accumulating: Here its 0
}
accumulate(first, last, sum);
first, last : first and last elements of range
whose elements are to be added
suppose array is 'a'.
sum : initial value of the sum
Eg: int sum=0;
accumulate(a.begin(),a.end(),sum);
accumulate(start, end, initial_sum);
// C++ program to demonstrate working of accumulate()
#include <iostream>
#include <numeric>
using namespace std;
// User defined function
int myfun(int x, int y)
{
// for this example we have taken product
// of adjacent numbers
return x * y;
}
int main()
{
// Initialize sum = 1
int sum = 1;
int a[] = { 5, 10, 15 };
// Simple default accumulate function
cout << "
Result using accumulate: ";
cout << accumulate(a, a + 3, sum);
// Using accumulate function with
// defined function
cout << "
Result using accumulate with"
"user-defined function: ";
cout << accumulate(a, a + 3, sum, myfun);
// Using accumulate function with
// pre-defined function
cout << "
Result using accumulate with "
"pre-defined function: ";
cout << accumulate(a, a + 3, sum, std::minus<int>());
return 0;
}
accumulate