本文介紹了如何循環遍歷地圖的 C++ 地圖?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
如何在 C++ 中循環遍歷 std::map
?我的地圖定義為:
How can 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, the above container 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?
推薦答案
老問題,但從 C++11 開始,其余答案已過時 - 您可以使用 范圍基于 for 循環 只需執行:
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++ 地圖?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!