This post will discuss how to get the sum of all elements present in a container in C++.

1. Using std::accumulate function

The recommended approach uses the standard algorithm std::accumulate defined in the <numeric> header. It accumulates all the values present in the specified range to the specified sum and returns the result.

Download  Run Code

Output:

The sum of the vector elements is 15

2. Using std::for_each function

Another efficient solution is to use std::for_each that performs a given operation on each of the elements in the specified range. The following code uses lambda expressions that were introduced with C++11.

Download  Run Code

Output:

The sum of the vector elements is 15

3. Using range-based for-loop

Another solution is to use a range-based for-loop to iterate the container and add each encountered element’s value to a result sum. Range-based for-loop was introduced in C++11.

Download  Run Code

Output:

The sum of the vector elements is 15

4. Using Iterator

We can also use iterators to process each element. The following program uses const_iterator that was introduced with C++11.

For C++98/03, we can easily convert the code to use begin() and end() functions instead that returns an iterator.

Download  Run Code

Output:

The sum of the vector elements is 15

That’s all about getting the sum of all elements present in a container in C++.