Home »
C++ STL
std::accumulate() function with example in C++ STL
C++ STL std::accumulate() function: Here, we are going to learn about the accumulate() function in C++ STL with example.
Submitted by Sanjeev, on April 23, 2019
C++ STL supports a variety of functions and templates to solve problems in different ways.
C++ STL std::accumulate() function
std::accumulate() function is used to accumulate all the values in the range [first, last] both inclusive to any variable initial_sum.
Default operation which accumulates function do is adding up all the elements but different operations can be performed.
Syntax
Syntax of accumulate() function:
accumulate(start, end, initial_sum);
Parameter(s)
- start: is the initial position of the iterator
- end: is the last position of the iterator.
Note: An additional argument can also be passed in the accumulate function which specifies the type of operation to be performed.
Syntax
Syntax of accumulate() function with additional argument:
accumulate(start, end, initial_sum, func);
Here, func is the additional operation which is to be performed.
C++ program to demonstrate example of std::accumulate() function
#include <bits/stdc++.h>
#include <vector>
using namespace std;
int main() {
// Initialization of vector
vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9};
// Taking initial sum as 0
int sum = 0;
cout << "\n Initial value of sum = " << sum << endl;
// Demonstration of accumulate function
// to sum all the elements of the vector
sum = accumulate(vec.begin(), vec.end(), sum);
cout << " Value of sum after accumulate = " << sum << endl;
// Changing value of initial_sum to 50
sum = 50;
cout << "\n Initial value of sum = " << sum << endl;
// Demonstration of accumulate function
// with the additional argument
// Here additional argument is used to
// subtract all the elements from the
// initial sum. Additional argument can be
// any valid function or operation
sum = accumulate(vec.begin(), vec.end(), sum, minus<int>());
cout << " Value of sum after accumulate function with optional argument = "
<< sum << endl;
return 0;
}
Output
Initial value of sum = 0
Value of sum after accumulate = 45
Initial value of sum = 50
Value of sum after accumulate function with optional argument = 5