如何循环通过地图的C ++映射? [英] How to loop through a C++ map of maps?
本文介绍了如何循环通过地图的C ++映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何循环使用C ++中的 std :: map
?
我的地图定义为:
std :: map< std :: string,std :: map< std :: string,std :: string> >
例如,这样保存这样的数据:
m [name1] [value1] =data1;
m [name1] [value2] =data2;
m [name2] [value1] =data1;
m [name2] [value2] =data2;
m [name3] [value1] =data1;
m [name3] [value2] =data2;
如何循环遍历此地图并访问各种值?
解决方案
旧问题,但剩下的答案是过时的C ++ 11 - 你可以使用基于循环的范围,只需执行以下操作:
std :: map< std :: string,std :: map< std :: string,std :: string>> MyMap中; (auto const& ent1:mymap)的
{
// ent1.first是(auto const& ent2:ent1.second)的
b $ b // ent2.first是第二个键
// ent2.second是数据
}
}
这应该比早期版本更干净,并避免不必要的副本。有些人赞成用引用变量的明确定义来替换注释(如果未使用,则会被优化):
<$ p (auto const& ent1:mymap)的$ p>
{
auto const& outer_key = ent1.first;
auto const& inner_map = ent1.second; (auto const& ent2:inner_map)
{
auto const& inner_key = ent2.first;
auto const& inner_value = ent2.second;
}
}
How would I loop through a std::map
in C++?
My map is defined as:
std::map< std::string, std::map<std::string, std::string> >
For example, this holds data like this:
m["name1"]["value1"] = "data1";
m["name1"]["value2"] = "data2";
m["name2"]["value1"] = "data1";
m["name2"]["value2"] = "data2";
m["name3"]["value1"] = "data1";
m["name3"]["value2"] = "data2";
How can I loop through this map and access the various values?
解决方案
Old question but the remaining answers are outdated as of C++11 - you can use a ranged based for loop and simply do:
std::map<std::string, std::map<std::string, std::string>> mymap;
for(auto const &ent1 : mymap) {
// ent1.first is the first key
for(auto const &ent2 : ent1.second) {
// ent2.first is the second key
// ent2.second is the data
}
}
this should be much cleaner than the earlier versions, and avoids unnecessary copies.
Some favour replacing the comments with explicit definitions of reference variables (which get optimised away if unused):
for(auto const &ent1 : mymap) {
auto const &outer_key = ent1.first;
auto const &inner_map = ent1.second;
for(auto const &ent2 : inner_map) {
auto const &inner_key = ent2.first;
auto const &inner_value = ent2.second;
}
}
这篇关于如何循环通过地图的C ++映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文