实现迭代器

  1. #include "stdafx.h" 
  2. namespace MyClass
  3. {
  4.     #define MAXCOUNT 255 
  5.     template<class T>
  6.     class MyvectorInt
  7.     {
  8.     public:
  9.         class Iterator
  10.         {
  11.         public:
  12.             Iterator( MyvectorInt<T> &vector, int iIndex ):m_vecotr( vector ), m_iIndex(iIndex){}
  13.             Iterator& operator++( )
  14.             {
  15.                 m_iIndex ++;
  16.                 return *this;
  17.             }
  18.             Iterator& operator=(const Iterator& other )
  19.             {
  20.                 m_iIndex = other.m_iIndex;
  21.                 return *this;
  22.             }
  23.             bool operator!=( const Iterator& other )
  24.             {
  25.                 return m_iIndex!=other.m_iIndex;
  26.             }
  27.             T* operator->() const
  28.             {
  29.                 return (T*)(this->m_vecotr.m_Data + m_iIndex);
  30.             }
  31.             T& operator*() const
  32.             {
  33.                 return this->m_vecotr.m_Data[m_iIndex];
  34.             }   
  35.         private:
  36.             int m_iIndex;
  37.             MyvectorInt<T> &m_vecotr;
  38.         };
  39.     private:
  40.         T m_Data[MAXCOUNT];
  41.         int m_iSize;
  42.     public:
  43.         MyvectorInt<T>()
  44.         {
  45.             m_iSize = 0;
  46.         }
  47.         Iterator begin()
  48.         {
  49.             return Iterator( *this, 0 );
  50.         }
  51.         Iterator end()
  52.         {
  53.             return Iterator( *this, m_iSize );
  54.         }
  55.         int size()
  56.         {
  57.             return m_iSize;
  58.         }
  59.         
  60.         Iterator insert( T &x )
  61.         {
  62.             if( m_iSize == MAXCOUNT )
  63.             {
  64.                 return Iterator( *this, m_iSize );
  65.             }
  66.             memcpy( m_Data+m_iSize, &x, sizeof(T) );
  67.             m_iSize ++;
  68.             return Iterator( *this, m_iSize -1 );
  69.         }
  70.     };
  71. }
  72. typedef struct _x
  73. {
  74.     int a;
  75.     int b;
  76. } X;
  77. int _tmain(int argc, _TCHAR* argv[])
  78. {
  79.     MyClass::MyvectorInt<X> vector;
  80.     X x;
  81.     forint i = 0; i < 10; i ++ )
  82.     {
  83.         x.a = 1;
  84.         x.b = 2;
  85.         vector.insert( x );
  86.     }
  87.     for( MyClass::MyvectorInt<X>::Iterator it = vector.begin(); it != vector.end(); it ++ )
  88.     {
  89.         printf( "%d/r/n", it->b );
  90.     }
  91.     return 0;
  92. }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值