17

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.

6
  • 1
    I'd like to swim the atlantic without getting in the water? Or do you just want to avoid writing the for loop yourself?
    – bmargulies
    Dec 28, 2012 at 18:19
  • I'm looking LINQ like functions as in C# Dec 28, 2012 at 18:20
  • 1
    They use loops, it's just not so evident.
    – Puppy
    Dec 28, 2012 at 18:26
  • I know behind the scenes is the loop. I want to use shortcut with just one line of code Dec 28, 2012 at 18:26
  • 8
    Why is this question closed as not constructive? It's a good question.
    – SmallChess
    Dec 2, 2015 at 1:02

2 Answers 2

29

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>
    
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, // initial value of the sum
        [](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; }
4
  • 3
    #include <numeric> is missing Dec 28, 2012 at 18:44
  • @ChesnokovYuriy fixed. GCC didn't catch that, thanks.
    – rubenvb
    Dec 28, 2012 at 20:37
  • Great example for introducing lambdas !
    – kebs
    May 7, 2014 at 12:49
  • 1
    For those trying to shorten the function call, try std::accumulate(bla.begin(), bla.end(), 0, [](const size_t previous, decltype(*bla.begin()) p) { return previous+p.second; });. Jul 5, 2016 at 8:27
5

Use std::accumulate. But it very likely will use loop behind the scenes.

8
  • how to use it? can you provide code sample? Dec 28, 2012 at 18:20
  • 5
    No. I have to feed my children now. Look for 4 parameter version.
    – Tomek
    Dec 28, 2012 at 18:21
  • Do you want your post to be marked as answer? I do not want to declare additional function to the 4th parameter and use some inline binding Dec 28, 2012 at 18:22
  • @ChesnokovYuriy then use a lambda.
    – rubenvb
    Dec 28, 2012 at 18:24
  • sure :) @BillyONeal did not know how to use lambda Dec 28, 2012 at 18:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.