【发布时间】:2014-08-14 05:31:44
【问题描述】:
我正在尝试打印嵌套的多图,但没有找到帮助我解决问题的方法(或此处的讨论)。
我通常打印多图的方式如下所示:
template<typename a, typename b>
void printMMap1(std::multimap<a, b>thing){
for (std::multimap<a,b>::iterator it = thing.begin(); it != thing.end(); it++){
std::cout << it->first << " : " << it->second << std::endl;
}
}
但现在我想用同样的动机来打印一个:
multimap<multimap<a,b>, multimap<c,d>> MAPname;
这似乎不起作用:
template<typename aa, typename bb, typename cc>
void printMMap(std::multimap<std::multimap<aa, bb>, std::multimap<aa, cc>>thing){
for (std::multimap<std::multimap<aa, bb>, std::multimap<aa, cc>>::iterator it = thing.begin(); it != thing.end(); it++){
std::cout << it->first.first << " : " << it->first.second << std::endl <<
it->second.first << " : " << it->second.second << std::endl;
}
}
任何帮助/建议将不胜感激!
感谢您的帮助。
_编辑:
利用 hansmaad 的例子,我想出了一些接近我想要的解决方案的东西(下):
//N.B: I removed the "auto"s for educational purposes (mostly for myself and other beginners)
template<typename a, typename b>
void print1(const std::multimap<a, b>& thing){
for (std::multimap<a,b>::const_iterator it = begin(thing); it != thing.end(); it++){
std::cout << it->first << " : " << it->second << std::endl;
}
}
template<typename aa, typename bb, typename cc>
void print2(const std::multimap<std::multimap<aa, bb>, std::multimap<aa, cc>>& thing){
std::multimap<std::multimap<aa, bb>, std::multimap<aa, cc>>::const_reverse_iterator it = thing.rbegin();
//why reverse iterator? Because I noticed that the loop which duplicates the output has a final iteration equal to the desired output, so I only use the last iteration i.e. going backwards ("rbegin")
std::multimap<aa, bb> keyMap = it->first;
std::multimap<aa, cc> valueMap = it->second;
std::cout << "key\n";
print1(keyMap);
std::cout << "value\n";
print1(valueMap);
}
这会打印出这个解决方案,它与我想要的结果接近 90%。例如它打印:
key
a_key1 : a_value1
a_key2 : a_value1
a_key2 : a_value2
a_key2 : a_value3
a_key3 : a_value1
a_key3 : a_value2
a_key3 : a_value3
a_key3 : a_value4
value
b_key1 : b_value1
b_key1 : b_value2
b_key1 : b_value3
b_key1 : b_value4
b_key2 : b_value1
b_key3 : b_value1
b_key4 : b_value1
b_key4 : b_value2
而我想打印相同的输出,尽管格式如下:
key value
a_key1 : a_value1 b_key1 : b_value1
a_key2 : a_value1 b_key1 : b_value2
a_key2 : a_value2 b_key1 : b_value3
a_key2 : a_value3 b_key1 : b_value4
a_key3 : a_value1 b_key2 : b_value1
a_key3 : a_value2 b_key3 : b_value1
a_key3 : a_value3 b_key4 : b_value1
a_key3 : a_value4 b_key4 : b_value2
略有不同。我闻到我很近了。
【问题讨论】:
-
你的意思是这似乎不起作用?
-
好吧,就像 hansmaad 后面所说的那样,multimap
&& multimap 没有 'first' 作为成员。我想打印==>“key1:value1,key2:value2,key3:value3”等,但我只能完成==>“key1:value1,key1:value1,key2:value2,key1:value1,key2 : value2, key3 : value3," 等等。它复制了输出。这有意义吗?