【问题标题】:C++ iterate through a template MapC++ 遍历模板 Map
【发布时间】:2012-01-14 20:10:40
【问题描述】:

当我有一个包含模板映射的模板类和typedef 在以下代码中声明的const_iterator 时,我如何遍历类外部的映射元素,主要是 fe 以打印它们输出?

template<class K, class V>
class template_map{
private:

    typedef typename std::map<K,V> TMap;
    TMap my_map;

public:
    typedef typename TMap::const_iterator const_iterator;
    ...
};

int main()
{

template_Map<int,double> Map1 //suppose that contains elements

?
}

更新: typedef 迭代器可以在类外使用吗?如果是,以什么方式?

【问题讨论】:

  • 你的主要功能有误。例如,完整的类型是template_map&lt;int,double&gt;。然后你可以说template_map&lt;int,double&gt;::const_iterator 来命名你的迭代器。您还必须在template_map&lt;K,V&gt; 的公共接口中公开my_map 的迭代器函数。

标签: c++ templates map iterator


【解决方案1】:

将 begin() 和 end() 成员添加到 template_Map(常量和非常量变体)。

const_iterator begin() const {
    return my_map.begin();
}
const_iterator end() const {
    return my_map.end();
}
iterator begin() {
    return my_map.begin();
}
iterator end() {
    return my_map.end();
}

我添加非常量版本只是为了界面完整性,在您的情况下可能不需要。 比主要:

typedef template_Map<x, y> template_MapXY;
template_MapXY Map1;
...
for ( template_MapXY::const_iterator it( Map1.begin() ), end( Map1.end() ); it != end; ++ it ) {
     ...
}

【讨论】:

    【解决方案2】:

    您需要在模板上定义返回迭代器的成员函数:

    template<class K, class V>
    class template_map{
    
    private:
    
    typedef typename std::map<K,V> TMap;
    TMap my_map;
    
    public:
        typedef typename TMap::const_iterator const_iterator;
        const_iterator begin() const { return my_map.begin(); }
        const_iterator end() const   { return my_map.end(); }
    };
    

    然后:

    int main()
    {
        template_map<int, int> m;
        // Populate map...
    
        // Then iterate...
        for (auto i = m.begin(); i != m.end(); i++)
        {
        }
    }
    

    但是,我不确定您在此处向std::map 添加了什么,为什么不直接使用它呢?

    【讨论】:

      【解决方案3】:

      我不明白您为什么要将 map 类与另一个类包装在一起。你为什么不std::map自己呢?

      std::map 的迭代通常是这样完成的:

      for(std::map<mykey, myvalue>::iterator it = mymap.begin(); it != mymap.end(); ++it)
      {
          somevar = it->first; // <<--- points to your key
          someothervar = it->second; // points to your value
      }
      

      【讨论】:

      • 这是必须的,不是我的选择。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 2022-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      相关资源
      最近更新 更多