Iterator

#include <iostream>

using namespace std;




template <typename T>
class Iterator
{
public:
    T& Value() { return *m_pValue; }
    Iterator<T>& operator=(const Iterator<T>& other)
    {
        this->m_pValue = other.m_pValue;
        return *this;
    }
    bool operator==(const Iterator<T>& other)
    {
        return this->m_pValue == other.m_pValue;
    }

    bool operator!=(const Iterator<T>& other)
    {
        return this->m_pValue != other.m_pValue;
    }
    
    void operator++(int)
    {
        m_pValue++;
    }
    
//protected:
public:
    T* m_pValue;
};



template <typename T>
class Container
{
public:
    virtual void PushBack(T)=0;
    virtual Iterator<T> Begin()=0;
    virtual Iterator<T> End()=0;
};

template <typename T>
class VectorContainer : public Container<T>
{
public:
    VectorContainer() { for (int i = 0; i < 128; i++) m_array[i] = -1; m_iCount = 0; }
    
    void PushBack(T);
    Iterator<T> Begin()
    {
        Iterator<T> iter;
        iter.m_pValue = &m_array[0];

        return iter;
    }
    Iterator<T> End()
    {
        Iterator<T> iter;
        iter.m_pValue = &m_array[m_iCount];

        return iter;
    }
    
    void Output();
    
private:
    T m_array[128];
    int m_iCount;
};



template <typename T>
void VectorContainer<T>::PushBack(T value)
{
    m_array[m_iCount++] = value;
}



int main(int argc, char *argv[])
{
    VectorContainer<int> vectorContainer;
    vectorContainer.PushBack(1);
    vectorContainer.PushBack(2);
    vectorContainer.PushBack(3);

    Iterator<int> iter = vectorContainer.Begin();
    for (; iter != vectorContainer.End(); iter++)
    {
        cout<<"value:"<<iter.Value()<<endl;
    }

    return 0;
}

 

posted @ 2014-12-22 14:12  stanley19861028  阅读(115)  评论(0编辑  收藏  举报