1

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 ?

1

1 Answer 1

1

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()); }
2
  • Note that there's a good chance you don't want the reference type to be value_type but value_type&. Also, this doesn't accomodate const ranges correctly.
    – Xeo
    Nov 30, 2012 at 10:52
  • Still doesn't work correctly for const ranges, since value_type const& isn't convertible to value_type& (hint: you need two typedefs).
    – Xeo
    Nov 30, 2012 at 10:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.