c++ Std::accumulate for unordered map

  accumulate, c++, dictionary, lambda

I have a function which should accumulate all the values in an unordered map:

int sum_val(std::unordered_map<char, int> vm){
    auto addition = [](int a, std::unordered_map<char, int>::iterator b){ return a + b->second; };
    return std::accumulate(vm.begin(), vm.end(), 0, addition);
}   

However, when I try to compile this, I get the following error:

 error: 
      no matching function for call to object of type '(lambda at markov_gen.cpp:11:21)'
        __init = __binary_op(__init, *__first);

markov_gen.cpp:11:21: note: candidate function not viable: no known conversion from
      'std::__1::__hash_map_iterator<std::__1::__hash_iterator<std::__1::__hash_node<std::__1::__hash_value_type<char, int>, void *>
      *> >::value_type' (aka 'pair<const char, int>') to 'std::unordered_map<char, int>::iterator' (aka
      '__hash_map_iterator<__hash_iterator<std::__1::__hash_node<std::__1::__hash_value_type<char, int>, void *> *> >') for 2nd
      argument
    auto addition = [](int a, ITER b){ return a + b->second; };

I’m a little confused why this binary operator addition won’t work. vm.begin() returns an iterator pointing to the first element in the unordered map and is therefore of type std::unordered_map<char, int>::iterator, and since the output of my accumulation should be an int, the left element in the lambda should always be an int while the right element should be the iterator as std::accumulate iterates through every key in the unordered map. Therefore, the operation of int + std::unordered_map<char, int>::iterator is well defined by my anonymous function. Where am I going wrong?

Source: Windows Questions C++

LEAVE A COMMENT