簡體   English   中英

定義用於遍歷不同容器類型的通用轉換迭代器

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

我有以下課程:

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

我經歷過: 通用迭代器變換迭代器 據我了解,轉換迭代器仍然需要您在模板參數中提供基礎容器迭代器。 因此,有沒有一種方法可以使用轉換迭代器在地圖鍵周圍定義自定義迭代器類型,並同時使其適用於不同類型的地圖容器?

如果您使用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;

您的beginend虛擬機只需要構造適當的迭代器:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM