How to sum all the values ​​on std :: map?

How to sum all the values ​​in the std::map<std::string, size_t> collection without using for a loop? The card is a private member of the class. Accumulation is performed when calling public functions.

I do not want to use boost or other third parties.

+7
source share
2 answers

You can do this with lambda and std::accumulate . Note that you need an updated 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, size_t> bla = {{"a", 1}, {"b", 3}}; const size_t result = std::accumulate(std::begin(bla), std::end(bla), 0, [](const size_t previous, const std::pair<const std::string,size_t>& p) { return previous+p.second; }); std::cout << result << "\n"; } 

For GCC and Clang: compile with -std=c++0x .

+11
source

Use std :: accumulate. But this will most likely use a loop behind the scenes.

+7
source

All Articles