Array sum in c++ stl
Here is an example of how to calculate the sum of elements in an array using the C++ STL (Standard Template Library):
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> arr = {1, 2, 3, 4, 5};
int sum = std::accumulate(arr.begin(), arr.end(), 0);
std::cout << "Sum: " << sum << std::endl;
return 0;
}
Explanation:
- We include the necessary headers:
<iostream>
for input/output,<numeric>
for theaccumulate
function, and<vector>
for the vector container. - We declare a
std::vector<int>
calledarr
and initialize it with some values. - We use the
std::accumulate
function from the<numeric>
header to calculate the sum of the elements in the vector. This function takes three arguments: the first iterator of the range (in this case,arr.begin()
), the last iterator of the range (in this case,arr.end()
), and an initial value for the sum (in this case,0
). - We store the result of the accumulation in the variable
sum
. - Finally, we output the sum using
std::cout
.
This code will output:
Sum: 15
The std::accumulate
function takes care of iterating over the elements in the range and adding them up. It is a convenient way to calculate the sum of elements in an array or container using the C++ STL.