迭代器模式

#include <iostream>
#include <memory>
#include <vector>

template <typename T, typename U>
class Iterator {
public:
    virtual U cur() = 0;
    virtual void next() = 0;
};

template <typename T, typename U>
class ConcreteIterator : public Iterator<T, U> {
public:
    ConcreteIterator(T* pc) { ct = pc; }
    U cur() override { return ct->at(currentIndex); }
    void next() override { currentIndex++; }
    bool done() { return currentIndex == ct->size(); }
private:
    T* ct;
    int currentIndex = 0;
};

template <typename T>
class Container {
public:
    ConcreteIterator<Container<int>, T> getIterator() {
        ConcreteIterator<Container<int>, T> iter(this);
        return iter;
    }
    void add(T d) { data_.push_back(d); }
    int size() { return data_.size(); }
    T at(int i) { return data_.at(i); }
private:
    std::vector<T> data_;
};

int main(int argc, char *argv[]) {
    Container<int> ci;
    ci.add(1);
    ci.add(2);
    ci.add(4);
    std::cout << ci.size() << std::endl;
    for(ConcreteIterator<Container<int>, int> iter = ci.getIterator(); !iter.done(); iter.next()){
        std::cout << "Cur iter data is " << iter.cur() << std::endl;
    }
    return 1;
}

  

posted @ 2022-02-25 18:02  南乡水  阅读(16)  评论(0编辑  收藏  举报