Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum all values in the std::map?

Tags:

c++

std

map

How to sum all values in std::map<std::string, size_t> collection without using for loop? The map resides as private member in a class. Accumulation is performed in public function call.

I do not want to use boost or other 3rd parties.

like image 487
Chesnokov Yuriy Avatar asked Dec 28 '12 18:12

Chesnokov Yuriy


1 Answers

You can do this with a lambda and std::accumulate. Note you need an up to date compiler (at least MSVC 2010, Clang 3.1 or GCC 4.6):

#include <numeric>
#include <iostream>
#include <map>
#include <string>
#include <utility>

int main()
{
    const std::map<std::string, std::size_t> bla = {{"a", 1}, {"b", 3}};
    const std::size_t result = std::accumulate(std::begin(bla), std::end(bla), 0,
                                          [](const std::size_t previous, const std::pair<const std::string, std::size_t>& p)
                                          { return previous + p.second; });
    std::cout << result << "\n";
}

Live example here.

If you use C++14, you can improve the readability of the lambda by using a generic lambda instead:

[](const std::size_t previous, const auto& element)
{ return previous + element.second; }
like image 88
rubenvb Avatar answered Oct 02 '22 20:10

rubenvb