我正在使用多级 map
map<string, map<string, map<string, int>>> _myMap;
如何仅使用最外层映射的迭代器访问整数值?
请帮助我也为 3 级 map 找到合适的引用。
最佳答案
您可以使用以下方法检索“第一个”内部整数(假设存在)。
int i = it->second.begin()->second.begin()->second;
要遍历所有值,您可以使用:
C++11:
for (/*const*/ auto& p1 : _myMap) { const std::string& s1 = p1.first; for (/*const*/ auto& p2 : p1.second) { const std::string& s2 = p2.first; for (/*const*/ auto& p3 : p2.second) { const std::string& s3 = p3.first; /*const*/ int& value = p3.second; // Do what you want. } } }
C++03:
typedef map<string, int> map3; typedef map<string, map3> map2; typedef map<string, map2> map1; for (map1::/*const_*/iterator it1 = _myMap.begin(), end1 = _myMap.end(); it1 != end1; ++it1) { const std::string& s1 = it1->first; for (map2::/*const_*/iterator it2 = it1->second.begin(), end2 = it1->second.end(); it2 != end2; ++it2) { const std::string& s2 = it2->first; for (map3::/*const_*/iterator it3 = it2->second.begin(), end3 = it2->second.end(); it3 != end3; ++it3) { const std::string& s3 = it3->first; /*const*/ int& value = it3->second; // Do what you want. } } }
关于C++ 3 级映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21629417/