Iterator

Basic Iterator

I create a base Iterator class which describe the interface of Iterator. After this, I can create the sub-class depend on the implementation. Ex: the array Type.

#include<iostream>

template<class Type>
class Iterator
{
public:
    virtual void next() {}
    virtual bool hasNext() {}
    virtual Type current() {}
};

template<class Type>
class ArrayIter : public Iterator<Type>
{
public:
    ArrayIter(Type *elem,int size): _start(elem),_current(0),_size(size) { }
    virtual void next() { if(_current <= _size) _current++; }
    virtual bool hasNext() { return (_current==_size) ? false : true; }
    virtual Type current() { return _start[_current]; }
private:
    Type *_start;
    int _current,_size;
};

template<class Type>
class Item
{
public:
    Item(int capacity): _capacity(capacity),_size(0) { _data = new Type [capacity]; }
    void pushItem(Type a) { if(_size < _capacity) _data[_size++] = a; else std::cerr<<"full!!\n"; }
    Iterator<Type> *createIter() { return new ArrayIter<Type>(_data,_size); }
private:
    Type *_data;
    int _size,_capacity;
};

int main()
{
    Item<int> *a = new Item<int> (10);

    for(int i=0;i<10;i+=2)
        a->pushItem(i);
    Iterator< int > *iter = a->createIter();

    while(iter->hasNext())
    {
        std::cout << iter->current() << ',';
        iter->next();
    }
    std::cout<<std::endl;
    return 0;
}

Composite Iterator

iterator with different class by using one!

class Interface { createIterator(); }
class Root : public Interface { }
class Leaf : public Interface { }

class Iterator 
{
    next();
    hasNext();
    current();
}
class RootIterator : public Iterator {}
class LeafIterator : public Iterator {}

int main()
{
    Iterator i = RootIterator.createIterator();
    while(i.hasNext())
    {
        i.current();
        i.next();
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License