C++ accumulate Function Guide
In C++, the accumulate function is used to calculate the sum of elements within a range. Its prototype is as follows:
template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );
first and last represent a range of iterators, with init as the initial value. The accumulate function will add all elements from first to last and return the sum.
For example, you can use the accumulate function like this:
#include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int sum = std::accumulate(vec.begin(), vec.end(), 0);
std::cout << "Sum of elements in vector: " << sum << std::endl;
return 0;
}
The code above will output:
Sum of elements in vector: 15