[英]C++ Check if Key Exists using Map within a Map
我有一个地图定义为map<string, map<string,int> > grandMap;
我需要检查内部地图是否有关键term
。 如果是这样,算一下。 这是我已经尝试过的方法:
auto countOccurrences(string term) -> int
{
int count = 0;
for(auto entry : grandMap)
{
if(entry->second.find(term)!=entry->second.end())
{
count++;
cout << "counted" << endl;
}
}
return count;
}
但我收到以下错误:
415.cpp:50:11: error: base operand of '->' has non-pointer type 'std::pair<const std::basic_string<char>, std::map<std::basic_string<char>, int> >'
415.cpp:50:37: error: base operand of '->' has non-pointer type 'std::pair<const std::basic_string<char>, std::map<std::basic_string<char>, int> >'
...这显然表明我试图获得第二个entry
,我认为这是grandMap的一个元素,但似乎并不完全符合我的意愿...
那么解决这个问题的正确方法是什么?
问题是您使用的是operator ->
而不是operator .
:
if (entry.second.find(term) != entry.second.end())
// ^ ^
另外,为避免过早的悲观化(有关定义,请参见Herb Sutter的GoTW ),您应该通过引用const
来接受term
arguments,并且还应该在基于范围的for
循环中使用auto const&
。
此外, count_if
标准算法似乎是您想要的:
// Using C++14's return type deduction for regular functions...
auto count(std::string const& term)
{
return std::count_if(std::begin(grandMap), std::end(grandMap),
[&] (decltype(grandMap)::value_type const& entry)
{
return (entry.second.find("hello") != std::end(entry.second));
});
}
这是一个完整的程序:
#include <map>
#include <string>
#include <algorithm>
#include <iostream>
std::map<std::string, std::map<std::string, int>> grandMap =
{ { "1", { { "hello", 42 }, { "hi", 1337 } } },
{ "2", { { "hello", 42 }, { "hello", 1729 } } }};
auto count(std::string const& term)
{
return std::count_if(std::begin(grandMap), std::end(grandMap),
[&] (decltype(grandMap)::value_type const& entry)
{
return (entry.second.find("hello") != std::end(entry.second));
});
}
int main()
{
std::cout << count("hello");
}
以及相应的现场例子 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.