美文网首页
c++实现模板迭代器

c++实现模板迭代器

作者: 一路向后 | 来源:发表于2022-02-23 21:51 被阅读0次

1.源码实现

#include <iostream>
#include <string>

using namespace std;

//迭代器基类
template<typename T>
class Iterater {
public:
    virtual ~Iterater() {}
    virtual void first() = 0;
    virtual void next() = 0;
    virtual bool isDone() = 0;
    virtual T currentItem() = 0;
};

//容器基类
template<typename T>
class Aggregate {
public:
    virtual ~Aggregate() {}
    virtual Iterater<T> *createIterater() = 0;
    virtual int getSize() = 0;
    virtual T getItem(int nIndex) = 0;
};

//具体迭代器
template<typename T>
class ConcreateIterater : public Iterater<T> {
private:
    Aggregate<T> *p_;
    int cur_index_;

public:
    ConcreateIterater(Aggregate<T> *agregate) : cur_index_(0), p_(agregate){}

    ~ConcreateIterater() {}

    void first()
    {
        cur_index_ = 0;
    }

    void next()
    {
        if(cur_index_ < p_->getSize())
        {
            cur_index_++;
        }
    }

    bool isDone()
    {
        if(cur_index_ > p_->getSize() - 1)
        {
            return true;
        }

        return false;
    }

    T currentItem()
    {
        return p_->getItem(cur_index_);
    }
};

//具体容器
template<typename T>
class ConcreateAggregate : public Aggregate<T> {
public:
    ConcreateAggregate(int nSize) : size_(nSize), data_(NULL)
    {
        data_ = new T[nSize];

        for(int i=0; i<nSize; i++)
        {
            data_[i] = i;
        }
    }

    Iterater<T> *createIterater()
    {
        return new ConcreateIterater<T>(this);
    }

    int getSize()
    {
        return size_;
    }

    T getItem(int nIndex)
    {
        if(nIndex < 0 || nIndex >= size_)
            return (T)-1;

        return data_[nIndex];
    }

private:
    int size_;
    T *data_;
};

int main()
{
    Aggregate<double> *pag = new ConcreateAggregate<double>(10);
    Iterater<double> *pcon = pag->createIterater();

    cout << "all value: " << endl;

    for(pcon->first(); !pcon->isDone(); pcon->next())
    {
        cout << "value: " << pcon->currentItem() << endl;
    }

    return 0;
}

2.编译源码

$ g++ -o test test.cpp -std=c++11

3.运行及其结果

$ ./test
all value: 
value: 0
value: 1
value: 2
value: 3
value: 4
value: 5
value: 6
value: 7
value: 8
value: 9

相关文章

网友评论

      本文标题:c++实现模板迭代器

      本文链接:https://www.haomeiwen.com/subject/dcsalrtx.html