其他分享
首页 > 其他分享> > 迭代器模式

迭代器模式

作者:互联网

迭代器的核心实现是:让容器对应的具体迭代器类中拥有该容器的引用成员变量。在创建迭代器时把容器对象的引用传给迭代器,那么迭代器就可以操作容器元素了。

Iterator的核心功能,就是提供了一种特定的方法,顺序访问一个容器中的各个元素,既不会暴露容器的内部设计细节(容器底层数据结构),又可以让外部代码透明的访问集合内部的所有元素

#include <QCoreApplication>
#include <iostream>
typedef int Object;
#define maxsize 5
using namespace std;


class Iterator{
 public:
  virtual void first() = 0;
  virtual void next() = 0;
  virtual bool IsDone() =0;
  virtual int currentItem() =0;
};

//抽象数组类
class Array{
 public:
    virtual Iterator* createrIterator() = 0;
    virtual Object getItem(int current_idex) = 0;
    int getSize(){
        return maxsize;
    }

};

//具体迭代器
class myIterator: public Iterator{
 public:

  myIterator(Array*pobj){
      m_Parry = pobj;
      m_iCurrentItem =0;
  }
  ~myIterator(){
      if (m_Parry != NULL){
          delete m_Parry;
      }
  }
  void first(){
      m_iCurrentItem = 0;
  }
  void next(){
      if(m_iCurrentItem < m_Parry->getSize()){
          m_iCurrentItem++;
      }
  }
  bool IsDone(){
      return (m_iCurrentItem == m_Parry->getSize());
  }
  Object currentItem(){
      return m_Parry->getItem(m_iCurrentItem);
  }

private:
  //迭代器的当前状态
  int m_iCurrentItem;
  //迭代器拥有的数组对象的引用(重要)
  Array *m_Parry;
};

//具体的数据集合类
class myArray: public Array{
 public:
    myArray(){
        for(int i=0; i<maxsize; i++){
            m_object[i] = i+10;
        }
    }
    ~myArray(){}
    Iterator* createrIterator(){
        //让迭代器持有一个容器的引用
        return new myIterator(this);
    }

    Object getItem(int current_idex){

        return m_object[current_idex];
    }
private:
    Object m_object[maxsize];
};



int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    Array * p = new myArray();
    Iterator* it = p->createrIterator();
    for(; !(it->IsDone()); it->next()){
        int n =it->currentItem();
        cout <<"current item is : "<< n <<endl;
    }
    delete p;
    delete it;
     return a.exec();
}

 

标签:iCurrentItem,迭代,int,virtual,Parry,模式,public
来源: https://blog.csdn.net/cindywry/article/details/111032997