There are four problems with this code:
- You have too many closing angle brackets.
- Your multimap probably shouldn't be named
multimap
. (Although this might not cause a compile error, it's pretty obvious that you shouldn't do it.)
- Dereferencing a multimap iterator gives a key-value pair, rather than just the value. So of course you can't sum these with
std::accumulate
directly.
- Even if you did this with a multiset instead of a multimap, so #3 wouldn't apply, passing
0
as the initial value will cause all the floats to be truncated as it would deduce type int
for the accumulator... so you would probably get the wrong answer.
It looks like you're stuck in 2003, since you actually wrote out the return type of equal_range
, so I guess no lambdas or range-for-loops for you.
pair<multimap<int32_t, float>::iterator,
multimap<int32_t, float>::iterator> range = M.equal_range(an_int);
float total = 0;
for (multimap<int32_t, float>::iterator I = range.first; I != range.second; ++I) {
total += I->second;
}
Or avoid equal_range
and that nasty declaration altogether...
float total = 0;
for (multimap<int32_t, float>::iterator I = M.lower_bound(an_int);
I != M.end() && I->first == an_int;
++I) {
total += I->second;
}
Edit: Okay, so you do have C++11 support. So you can do this:
auto range = M.equal_range(an_int);
float total = accumulate(range.first, range.second, 0.0,
[](float x, pair<int32_t, float> y) { return x + y.second; });
(Note: If you have C++14 support, you can even replace pair<int32_t, float>
by auto
in the lambda.)