Sunday, April 22, 2012

How to define your own container and iterator

I want to define a simple wrapper class of “std” container. The meaning of the following code is to provide a Qt style container interface for some legacy C++ code segments with Qt. The key point below is

typedef typename map<KEY,VALUE>::iterator iterator;
Because the compiler does not know the following token, so we need explicitly declare “typename” to tell the compiler that the coming token is the name of a type.
The following is the whole declaration and implementation. 



   1:  #ifndef MYMAP_H
   2:  #define MYMAP_H
   3:   
   4:  #include <map>
   5:  using namespace std;
   6:   
   7:  template <class KEY, class VALUE>
   8:  class MyMap
   9:  {
  10:  public:
  11:      MyMap();
  12:      bool contains( KEY data );
  13:      VALUE value( KEY data );
  14:      void insert( KEY key, VALUE value );
  15:      typedef typename map<KEY,VALUE>::iterator iterator;
  16:  private:
  17:      map<KEY,VALUE> _data;
  18:  };
  19:   
  20:  template<class KEY, class VALUE>
  21:  MyMap<KEY, VALUE>::MyMap()
  22:  {
  23:      return;
  24:  }
  25:   
  26:  template<class KEY, class VALUE>
  27:  bool MyMap<KEY, VALUE>::contains( KEY data )
  28:  {
  29:      MyMap<KEY, VALUE>::iterator iter = this->_data.find( data );
  30:      if( iter != this->_data.end() )
  31:      {
  32:          return true;
  33:      }
  34:      else
  35:      {
  36:          return false;
  37:      }
  38:  }
  39:  //
  40:  template<class KEY, class VALUE>
  41:  VALUE MyMap<KEY, VALUE>::value( KEY data )
  42:  {
  43:      MyMap<KEY, VALUE>::iterator iter = this->_data.find( data );
  44:      if( iter != this->_data.end() )
  45:      {
  46:          return iter->second;
  47:      }
  48:      else
  49:      {
  50:          return 0;
  51:      }
  52:  }
  53:  //
  54:  template<class KEY, class VALUE>
  55:  void MyMap<KEY, VALUE>::insert( KEY key, VALUE value )
  56:  {
  57:      this->_data.insert( make_pair( key, value ) );
  58:      return;
  59:  }
  60:   
  61:  #endif

No comments:

Post a Comment