我想遍历多重映射中的所有项目 <string,map<string,int>>
但是每个键只有一次,但我无法让它工作,这是我用来迭代的代码:
for(multimap <string, map <string, int> >::iterator it = myMultimap.begin(); it != myMultimap.end(); it =myMultimap.upper_bound(it->first)){
//i read that myMultimap.upper_bound(it->first) get the elements of the same key
pair< multimap <string,map <string, int> >::iterator , multimap <string,map <string, int> >::iterator > ret;
ret = myMultimap.equal_range(it->first);
for(multimap <string, map <string, int> >::iterator it2 = ret.first; it2 != ret.second; it2++){
//here i just want to print map <string , int>
cout << (*it2).second.first << endl;
cout << (*it2).second.second << endl;
}
}
当我运行它时,我得到 class std::map<std::basic_string<char>, int>’ don't have a member called ‘first’
second.second 同样如此。对不起,我的英语不是我的母语。
最佳答案
让我们自己开始吧
typedef std::map<std::string, int> InnerMap;
typedef std::multimap<std::string, InnerMap> StringMap;
StringMap myMultimap;
现在,那个外循环
for (StringMap::iterator it = myMultimap.begin(); it != myMultimap.end(); ++it)
{
std::cout << "[" << it->first << "]:";
for (InnerMap::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2)
{
std::cout << " " << it2->first << ":" << it2->second;
}
std::cout << '\n';
}
如果你有 C++11,我们还可以使用 auto 使事情变得更简单
for (auto it = myMultimap.begin(); it != myMultimap.end(); ++it)
{
std::cout << "[" << it->first << "]:";
for (auto it2 = it->second.begin(); it2 != it->second.end(); ++it2)
{
std::cout << " " << it2->first << ":" << it2->second;
}
std::cout << '\n';
}
我们在做什么:
for (StringMap::iterator it = myMultimap.begin(); it != myMultimap.end(); ++it)
这会遍历所有 std::pair<std::string /*key*/, InnerMap /*value*/>
实际上构成外部多重映射的元素。如果您有一个 key 两次,您将看到两个条目。
it->first
是std::string
当前 multimap 条目的键,it->second
是InnerMap
当前条目的值。
for (InnerMap::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2)
这遍历了 std::pair<std::string, int>
map 的 InnerMap 元素,即此 multimap 插槽的值。
--- 编辑 ---
最终,使用 C++11,您可以使用基于范围的 for(不知道为什么我认为这会更困惑)
// use 'auto&' so we take a reference instead of a copy.
for (auto& it : myMultimap)
{
std::cout << "[" << it.first << "]:";
for (auto it2 : it.second)
{
std::cout << " " << it2.first << ":" << it2.second;
}
std::cout << '\n';
}
请注意,在这种情况下,我们现在使用“.”而不是“->”。这是因为我们实际上看到的是 multimap/map 中的每个元素 ( std::pair<...>
),而不是一个简单的迭代器。即 it
类型为 std::pair<std::string, InnerMap>&
和 it2
类型为 std::pair<std::string, int>&
.
关于c++ - 遍历 multimap <string, map <string,int>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20063242/