sum of elements in c++ stl
To find the sum of elements in C++ using the STL (Standard Template Library), you can follow these steps:
- Include the necessary header file:
#include <numeric>
The <numeric>
header file contains functions for performing numeric operations, such as calculating the sum.
- Create a container and populate it with elements:
std::vector<int> numbers = {1, 2, 3, 4, 5};
In this example, we're using a std::vector<int>
container to store the numbers.
- Use the
std::accumulate
function:
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
The std::accumulate
function takes three arguments: the beginning iterator of the container (numbers.begin()
), the ending iterator of the container (numbers.end()
), and an initial value for the sum (0
in this case). It returns the sum of all the elements in the range.
- Print the result:
std::cout << "Sum: " << sum << std::endl;
This line of code prints the sum of the elements to the console.
Putting it all together, here's the complete code:
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << std::endl;
return 0;
}
When you run this code, it will output:
Sum: 15
This is the sum of all the elements in the numbers
vector.