使用C++实现迭代器模式的完整源代码
迭代器是一种行为设计模式,它允许客户端按顺序访问集合中的元素,而无需了解其底层表示。迭代器模式在C++中广泛使用,并且可以帮助我们更有效地管理和操作数据容器。
下面是使用C++实现迭代器模式的完整源代码:
#include <iostream>
#include <vector>
using namespace std;
// 迭代器接口类
template <class T>
class Iterator {
public:
virtual bool hasNext() = 0;
virtual T next() = 0;
};
// 具体迭代器类
template <class T>
class ConcreteIterator : public Iterator<T> {
public:
ConcreteIterator(vector<T> vec) : m_vec(vec), m_index(0) {}
bool hasNext() override {
return m_index < m_vec.size();
}
T next() override {
return m_vec[m_index++];
}
private:
vector<T> m_vec;
int m_index;
};
// 容器接口类
template <class T>
class Container {
public:
virtual Iterator<