【问题标题】:Getting the Iterator for an inner STL Container?获取内部 STL 容器的迭代器?
【发布时间】:2010-11-26 20:25:18
【问题描述】:

我在尝试获取内部子容器的迭代器时遇到了麻烦。

基本上想象一下这个简化的代码:

typedef map<string, map<string, map> > double_map;

double_map dm;
.. //some code here

for(double_map::iterator it = dm.begin(); it != dm.end(); it++){
    //some code here
    it->first // string
    it->second // <---- this is the 2nd map, how do i get its iterator so I can wrap it 
                       //in a for loop like above?
}

我需要能够在不对每个内部容器使用 typedef 的情况下做到这一点,有没有办法为内部容器获取迭代器?我的结构有 4 个内部容器,我需要遍历它们。

【问题讨论】:

    标签: stl iterator containers


    【解决方案1】:

    (注意,下面的sn-ps中没有编译。)

    for(double_map::iterator it = dm.begin(); it != dm.end(); it++){
        //some code here
        it->first; // string
        it->second.begin();
        it->second.end();
    }
    

    编辑:如果我正确理解您的评论,您想了解内部映射的迭代器的类型。如果是这样,这是一种方法:

    double_map::mapped_type::iterator inner_iter = it->second.begin();
    

    在我的脑海中,这也应该有效:

    double_map::value_type::second_type::iterator inner_iter = it->second.begin();
    

    【讨论】:

    • 对不起,这不是我的意思,我的意思是我需要将这些迭代器存储在 inner_type::iterator it2 = it->second.begin() 中,然后使用这些迭代器进行循环
    • 啊,就是这样!为什么我没有想到 mapped_type 和 value_type,是的,这正是我所需要的。谢谢!
    • 但是当有 3 或 4 层深的子容器时,我猜你必须做 double_map::mapped_type::mapped_type::mapped_type 嗯,幸运的是我中途有一个 typedef
    【解决方案2】:

    简单:

    typedef map<string, map> inner_map; //Typedef for readability
    typedef map<string, inner_map > double_map;
    
    double_map dm;
    .. //some code here
    for(double_map::iterator it = dm.begin(); it != dm.end(); it++){
        //some code here
        it->first // string
        inner_map &innerMap(it->second); //Reference to the inner map for readability
        for(inner_map::iterator it2 = innerMap.begin(); it2 != innerMap.end(); ++it2) {
            //Do whatever you like
        }
    }
    

    【讨论】:

    • 那是我的后备选项,但子容器的级别很少,我想在不为每个子容器使用 typedef 的情况下保持它的通用性。基本上我正在尝试在没有 typedef 的情况下做到这一点
    猜你喜欢
    • 2013-04-16
    • 2015-06-06
    • 2011-12-25
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 2011-01-15
    相关资源
    最近更新 更多