【问题标题】:C++ 3 level mapC++ 3级地图
【发布时间】:2014-03-04 23:07:15
【问题描述】:

我正在使用多级地图

map<string, map<string, map<string, int>>> _myMap;

如何仅使用最外层映射的迭代器访问整数值?

请帮助我找到适合 3 级地图的参考。

【问题讨论】:

  • 你不能在第二个和第三个映射中没有一个整数这样的东西。需要指定第二个和第三个map的key才能获取整数。
  • 此外,容器容器容器具有真正的代码气味。您应该以另一种方式看待建模。

标签: c++ map iteration stdmap


【解决方案1】:

您可以使用以下方法检索“第一个”内部 int(假设存在)。

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.
            }
        }
    }
    

【讨论】:

  • 如何访问更多的整数值?
【解决方案2】:
int myInt = (((*it).second)["index"])["index"];

您还可以使用迭代器重新生成新地图并通过它进行迭代。

【讨论】:

  • 我相信你的意思是it-&gt;second["index"]["index"]
  • 嗯,我现在很困惑,你的看起来更好但不一样吗?
  • @Mayerz second 不是函数。
  • 你不能在second 后面加上() - 这不是一个函数。
  • 仍然不正确。你的优先*(it.second),你的意思是(*it).second
猜你喜欢
  • 2015-01-13
  • 1970-01-01
  • 2021-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多