#include #include #include using namespace std; class Iterator { public: virtual bool has_next() = 0; virtual int next() = 0; virtual ~Iterator() = default; }; class IntContainer { private: vector v; public: void add_i(int i) { v.push_back(i); } shared_ptr begin(); }; class IntIterator : public Iterator { vector& v; int index; public: IntIterator(vector& v) : v(v), index(0) {} virtual bool has_next() { return index != v.size(); } virtual int next() { index += 1; return v[index - 1]; } }; shared_ptr IntContainer::begin() { return make_shared(this->v); } int main() { IntContainer c; c.add_i(1); c.add_i(3); c.add_i(5); c.add_i(6); // When you want to design a new container, you just // implement a iterator, so user don't have to care the // detail how the container work. auto v = c.begin(); while (v->has_next()) { cout << v->next() << endl; } }