我在iOS / ObjC项目中有一个cpp类。它使用以下地图:
std::map <std::string, int> testMap;
我知道我可以&#34;数&#34;通过testMap.count在该映射中出现给定键的次数。但是,如何计算该地图中给定值的出现次数?
e.g。假设有以下地图:
<Anna, 5>
<Brian, 4>
<Cesar, 4>
<Danny, 3>
- &GT;所以,如果我寻找价值的数量&#34; 4&#34;该函数应返回2,对于值&#34; 5&#34;和&#34; 3&#34;分别应该为每个返回1,否则为0 ......
提前致谢!
答案 0 :(得分:4)
最简单的方法可能是使用std::count_if
和适当的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;
});
这只是遍历地图并计算所有符合谓词的元素。
答案 1 :(得分:2)
可以使用基于声明的范围简单地完成:)
size_t count = 0;
int value = 4;
for ( auto &p : testMap ) count += p.second == value;
有时使用基于范围的语句看起来比使用标准算法std :: count_if更具可读性。:)
另一方面,如果多次使用此操作,则最好使用该算法。例如
int value = 4;
size_t n = std::count_if( std::begin( testMap ), std::end( testMap ),
[&value]( const std::pair<const std::string, int> &p )
{
return p.second == value;
} );
您还可以与算法
的调用分开定义lambdaint value;
size_t n;
auto IsEqual = [&value]( const std::pair<const std::string, int> &p )
{
return p.second == value;
};
value = 4;
n = std::count_if( std::begin( testMap ), std::end( testMap ), IsEqual );
//...
value = 5;
n = std::count_if( std::begin( testMap ), std::end( testMap ), IsEqual );