如何从外部开始循环嵌套的std :: map?
问题描述:
我的谷歌技能让我失望=(如何从外部开始循环嵌套的std :: map?
我有以下地图:
std::map<std::string, std::map<std::string, std::string>> spriteSheetMap;
我试图做到这一点:
for (auto &animationKey : killerRabbit->spriteSheetMap) {
for (auto &animation : animationKey) {
//why doesn't this work?
}
}
实际的错误:
Invalid range expression of type 'std::__1::pair<const std::__1::basic_string<char>, std::__1::map<std::__1::basic_string<char>, std::__1::basic_string<char>, std::__1::less<std::__1::basic_string<char> >, std::__1::allocator<std::__1::pair<const std::__1::basic_string<char>, std::__1::basic_string<char> > > > >'; no viable 'begin' function available
答
第一个循环调用begin()
,它返回std::pair
(即value_type
of std::map
's)。因此,像这样迭代一对,没有多大意义。我想你想要的是:
for (auto &animation : animationKey.second) {
这将遍历内部映射。请记住,animation
会发生同样的情况:animation
将会是一对,其中animation.first
指的是密钥,而animation.second
指的是该值。
答
错误是说它不能迭代一对。下面解决了这个问题,因为您在第一个循环中通过迭代映射获得键 - 值对结果。
for (auto &animation : animationKey.second)
参见map.begin()看到的实施例中的第一环的输出对,而不是值来自动变量如何。
您应该指定它在您的问题中不起作用 - 您得到的是什么错误,或者您的输出是什么意外。 – Pyrce 2013-04-04 00:32:51
@Pyrce 糟糕,增加了错误,令人困惑的是第一个循环有效,而第二个循环是相同类型的,我不能在这个周围扭曲我的头像s = s – Hobbyist 2013-04-04 00:35:17
杀手rabit今天已经结束了:) – 2013-04-04 00:42:49