c++iosalgorithmdictionaryrange-based-loop

How to count the number of a given VALUE(!) in a C++ map?


I do have a cpp class in an otherwise iOS/ObjC project. It uses the following map:

std::map <std::string, int> testMap;

I do know that I can "count" the number of appearances of a given key in that map via testMap.count. But how do I count the number of appearances of a given value in that map?

e.g. suppose to have the following map:

<Anna, 5>
<Brian, 4>
<Cesar, 4>
<Danny, 3>

--> So if I look for the number of value "4" the function should return 2, for values "5" and "3" respectively it should return 1 for each, otherwise 0...

Thanks in advance!


Solution

  • The easiest way is probably to use std::count_if with an appropriate lambda:

    int value = 4; // or something else
    
    std::count_if(std::begin(testMap),
                  std::end  (testMap),
                  [value](std::pair<std::string, int> const &p) {
                    return p.second == value;
                  });
    

    This simply walks through the map and counts all elements that fit the predicate.