C++ 3 级映射

标签 c++ dictionary iteration stdmap

我正在使用多级 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/

相关文章:

dictionary - 如何克隆字典对象?

javascript - react : Looping through an array within a state

python - 在 Python 中使用列表方法加速 for 循环

Python-如何获取循环中的最后一行

c++ - 在 C++ 中调用 system() 的问题

c# - Dictionary.Values.ToArray() 的顺序是什么?

c++ - 如何通过引用传递参数给模板类的成员函数?

vb.net - 在 vb.net 中从数据表中打印行的更好方法

c++ - 从 BaseClass* 到 DerivedClass* 的无效转换

c++ - 向 std::cout 添加 "prompt"消息的最佳方法