[英]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.