#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
Code Example |
---|
Cpp :: c++ split string by space into array |
Cpp :: c ++ splitlines |
Cpp :: min element in vector c++ |
Cpp :: c++ elif |
Cpp :: size() in c++ SET |
Cpp :: transformer in nlp |
Cpp :: doubly linked list code in c++ |
Cpp :: factorial of large number |
Cpp :: string format decimal places c++ |
Cpp :: c++ client service ros |
Cpp :: c++ changing string to double |
Cpp :: Traversing a C++ Array |
Cpp :: string reverse iterator c++ |
Cpp :: resize vector c++ |
Cpp :: il2cpp stuck unity |
Cpp :: how to take full sentence in c++ |
Cpp :: User defined functions and variables in C++ programming |
Cpp :: how to remove the scroll bar in pyqt6 |
Cpp :: c++ multiply char |
Cpp :: dequeue c++ |
Cpp :: sliding window c++ |
Cpp :: how to print a word in c++ |
Cpp :: c++ queue |
Cpp :: c++ swap function |
Cpp :: #define in cpp |
Cpp :: vector iterator in c++ |
Cpp :: array of charcter c++ |
Cpp :: c++ unordered_map initialize new value |
Cpp :: binary multiplication |
Cpp :: logisch oder |