// Iterator interface
class Iterator {
public:
virtual bool hasNext() = 0;
virtual int next() = 0;
};
// Concrete Iterator (Array)
class ArrayIterator : public Iterator {
private:
int arr[5] = {1, 2, 3, 4, 5};
int index = 0;
public:
bool hasNext() override {
return index < 5;
}
int next() override {
return arr[index++];
}
};
// Concrete Iterator (Vector)
class VectorIterator : public Iterator {
private:
std::vector<int> vec = {6, 7, 8, 9, 10};
// 註: Iterator 是一種設計模式,實作的資料結構內部再度使用程式語言所提供的內建 Iterator 也不少見
// 這時就更體現出迭代器模式可以隱藏內部實作細節的好處
std::vector<int>::iterator it;
public:
VectorIterator() {
it = vec.begin();
}
bool hasNext() override {
return it != vec.end();
}
int next() override {
return *(it++);
}
};
// Aggregate interface
class Aggregate {
public:
virtual Iterator* createIterator() = 0;
};
// Concrete Aggregate
class ConcreteAggregate : public Aggregate {
public:
Iterator* createIterator() override {
/* 可以自行選擇要使用哪一種 iterator 的底層實作 (簡略範例) */
// 1. Array
return new ArrayIterator();
// 2. Vector
return new VectorIterator();
}
};
// Client
int main() {
Aggregate* aggregate = new ConcreteAggregate();
Iterator* iterator = aggregate->createIterator();
while(iterator->hasNext()) {
std::cout << iterator->next() << std::endl;
}
}
Iterator 非常適合與許多設計模式搭配
External Iterator:
std::vector<int> vec = {1, 2, 3};
for(auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << std::endl;
}
Internal Iterator:
std::vector<int> vec = {1, 2, 3};
std::for_each(vec.begin(), vec.end(), [](int n) {
std::cout << n << std::endl;
});