简体   繁体   English

定义用于遍历不同容器类型的通用转换迭代器

[英]Defining a generic transform iterator for iterating over different container types

I have a class along the following lines : 我有以下课程:

class ArraySim{

  public: 
     DataStructure* ds;
     ArraySim(bool which){
        if(true)
           ds = new STDMap();
        else 
           ds = new HashMap();
     }
     value_type& operator[](int idx){
          return ds->getValAtIndex(idx);
     }

     //define a  custom iterator type that can be used to iterate over both std::map and boost::unordered //map keys.
} 

class DataStructure{

    vitrual value_type& getValAtIndex(int idx)=0;
};

class STDMap: public DataStructure{
   //Class that wraps a std::map object and implements the virtual method to return the value against a //particular index(key)
};

class HashMap: publlic DataStructure{
    //Class that wraps a boost::unordered_map object and implements the virtual method to return the value //against a particular index(key)
} 

I have been through : Generic Iterator and Transform Iterator . 我经历过: 通用迭代器变换迭代器 As I understand it , transform iterator still requires you to give the underlying container iterator in the template arguments. 据我了解,转换迭代器仍然需要您在模板参数中提供基础容器迭代器。 So is there a way I can use transform iterator to define a custom iterator type around the map keys and at the the same time make it work for different types of map containers ? 因此,有没有一种方法可以使用转换迭代器在地图键周围定义自定义迭代器类型,并同时使其适用于不同类型的地图容器?

If you're using Boost, you can use any_range . 如果您使用Boost,则可以使用any_range

typedef any_range<value_type, boost::forward_pass_traversal_tag,
  value_type &, std::ptrdiff_t> range;
typedef any_range<value_type, boost::forward_pass_traversal_tag,
  const value_type &, std::ptrdiff_t> const_range;
typedef range::iterator iterator;
typedef const_range::const_iterator const_iterator;

virtual iterator begin() = 0;
virtual iterator end() = 0;
virtual const_iterator begin() const = 0;
virtual const_iterator end() const = 0;

Your begin and end virtuals just need to construct the appropriate iterator: 您的beginend虚拟机只需要构造适当的迭代器:

iterator begin() { return iterator(object.begin()); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM