59 lines
1.1 KiB
C++
59 lines
1.1 KiB
C++
#include <iostream>
|
|
#include <memory>
|
|
#include <vector>
|
|
|
|
using namespace std;
|
|
|
|
class Iterator {
|
|
public:
|
|
virtual bool has_next() = 0;
|
|
virtual int next() = 0;
|
|
virtual ~Iterator() = default;
|
|
};
|
|
|
|
class IntContainer {
|
|
private:
|
|
vector<int> v;
|
|
public:
|
|
void add_i(int i) {
|
|
v.push_back(i);
|
|
}
|
|
|
|
shared_ptr<Iterator> begin();
|
|
};
|
|
|
|
class IntIterator : public Iterator {
|
|
vector<int>& v;
|
|
int index;
|
|
public:
|
|
IntIterator(vector<int>& v) : v(v), index(0) {}
|
|
virtual bool has_next() {
|
|
return index != v.size();
|
|
}
|
|
|
|
virtual int next() {
|
|
index += 1;
|
|
return v[index - 1];
|
|
}
|
|
};
|
|
|
|
shared_ptr<Iterator> IntContainer::begin() {
|
|
return make_shared<IntIterator>(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;
|
|
}
|
|
}
|