This post will discuss how to find the sum of all values in the map in C++.

1. Using std::accumulate

A simple solution to find the sum of all values in the map is using the std::accumulate function, defined in the <numeric> header. The idea is to overwrite its default behavior with a binary predicate passed in the optional fourth parameter, which extracts the second element of each entry and accumulates its sum. For example,

Download  Run Code

 
Since C++14, we can improve the readability of the binary predicate with auto keyword:

Download  Run Code

 
For multiple invocations to the std::accumulate function, we can construct a class/struct with operator() overload (a functor).

Download  Run Code

2. Using boost library

Alternatively, we can use Boost.Range library to find the sum of all values in the map. It has the boost::accumulate algorithm, which can be used with adaptors to find the desired sum. The following code example shows the invocation of this function:

Download Code

That’s all about finding the sum of all values in the map in C++.