adi
adi

Reputation: 590

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 ?

Upvotes: 1

Views: 370

Answers (1)

ecatmur
ecatmur

Reputation: 157484

If you're using Boost, you can use 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:

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

Upvotes: 1

Related Questions