迭代器模式詳解
1. 定義與意圖
迭代器模式(Iterator Pattern)?是一種行為設計模式,它提供一種方法順序訪問一個聚合對象中的各個元素,而又不暴露該對象的內部表示。
主要意圖:
為不同的聚合結構提供統一的遍歷接口。
將遍歷數據的職責與聚合對象本身分離,簡化聚合接口。
支持以不同方式遍歷同一個聚合(如前序、中序、后序遍歷二叉樹)。
2. 模式結構
迭代器模式包含以下幾個角色:
Iterator(迭代器接口):定義訪問和遍歷元素的接口。
ConcreteIterator(具體迭代器):實現迭代器接口,跟蹤遍歷的當前位置。
Aggregate(聚合接口):定義創建相應迭代器對象的接口。
ConcreteAggregate(具體聚合):實現創建相應迭代器的接口,返回具體迭代器的實例。
3. 適用場景
需要訪問聚合對象的內容而不暴露其內部表示
支持對聚合對象的多種遍歷方式
為遍歷不同的聚合結構提供統一的接口
4. 優點
單一職責原則:將遍歷算法與聚合對象分離
開閉原則:可以引入新的迭代器而不修改現有代碼
可以并行遍歷同一聚合,因為每個迭代器都有自己的狀態
可以暫停遍歷并在需要時繼續
5. 缺點
對于簡單的集合可能過于復雜
某些情況下,使用專門的遍歷方法可能比迭代器更高效
C++ 實現例子
例子1:自定義數組容器的迭代器
#include <iostream>
#include <stdexcept>template <typename T, size_t SIZE>
class Array {
private:T data[SIZE];public:// 迭代器類class Iterator {private:T* ptr;public:explicit Iterator(T* p) : ptr(p) {}// 前置++Iterator& operator++() {++ptr;return *this;}// 后置++Iterator operator++(int) {Iterator temp = *this;++ptr;return temp;}T& operator*() const {return *ptr;}T* operator->() const {return ptr;}bool operator==(const Iterator& other) const {return ptr == other.ptr;}bool operator!=(const Iterator& other) const {return !(*this == other);}};// const迭代器類class ConstIterator {private:const T* ptr;public:explicit ConstIterator(const T* p) : ptr(p) {}ConstIterator& operator++() {++ptr;return *this;}ConstIterator operator++(int) {ConstIterator temp = *this;++ptr;return temp;}const T& operator*() const {return *ptr;}const T* operator->() const {return ptr;}bool operator==(const ConstIterator& other) const {return ptr == other.ptr;}bool operator!=(const ConstIterator& other) const {return !(*this == other);}};// 獲取開始迭代器Iterator begin() {return Iterator(data);}Iterator end() {return Iterator(data + SIZE);}ConstIterator begin() const {return ConstIterator(data);}ConstIterator end() const {return ConstIterator(data + SIZE);}ConstIterator cbegin() const {return ConstIterator(data);}ConstIterator cend() const {return ConstIterator(data + SIZE);}T& operator[](size_t index) {if (index >= SIZE) {throw std::out_of_range("Index out of range");}return data[index];}const T& operator[](size_t index) const {if (index >= SIZE) {throw std::out_of_range("Index out of range");}return data[index];}size_t size() const {return SIZE;}
};// 使用示例
int main() {Array<int, 5> arr = {1, 2, 3, 4, 5};// 使用迭代器遍歷std::cout << "Using iterator: ";for (auto it = arr.begin(); it != arr.end(); ++it) {std::cout << *it << " ";}std::cout << std::endl;// 使用范圍for循環(基于迭代器)std::cout << "Using range-based for: ";for (const auto& item : arr) {std::cout << item << " ";}std::cout << std::endl;return 0;
}
例子2:二叉樹的中序遍歷迭代器
#include <iostream>
#include <stack>
#include <memory>template <typename T>
struct TreeNode {T value;std::shared_ptr<TreeNode> left;std::shared_ptr<TreeNode> right;TreeNode(T val) : value(val), left(nullptr), right(nullptr) {}
};template <typename T>
class BinaryTree {
private:std::shared_ptr<TreeNode<T>> root;public:BinaryTree() : root(nullptr) {}void setRoot(std::shared_ptr<TreeNode<T>> node) {root = node;}// 中序遍歷迭代器class InOrderIterator {private:std::stack<std::shared_ptr<TreeNode<T>>> stack;std::shared_ptr<TreeNode<T>> current;void pushLeft(std::shared_ptr<TreeNode<T>> node) {while (node) {stack.push(node);node = node->left;}}public:explicit InOrderIterator(std::shared_ptr<TreeNode<T>> root) {current = nullptr;pushLeft(root);if (!stack.empty()) {current = stack.top();stack.pop();}}T& operator*() const {return current->value;}InOrderIterator& operator++() {if (current->right) {pushLeft(current->right);}if (stack.empty()) {current = nullptr;} else {current = stack.top();stack.pop();}return *this;}bool operator!=(const InOrderIterator& other) const {return current != other.current;}bool hasNext() const {return current != nullptr;}};InOrderIterator begin() {return InOrderIterator(root);}InOrderIterator end() {return InOrderIterator(nullptr);}
};// 使用示例
int main() {// 創建二叉樹: // 1// / \// 2 3// / \// 4 5auto root = std::make_shared<TreeNode<int>>(1);root->left = std::make_shared<TreeNode<int>>(2);root->right = std::make_shared<TreeNode<int>>(3);root->left->left = std::make_shared<TreeNode<int>>(4);root->left->right = std::make_shared<TreeNode<int>>(5);BinaryTree<int> tree;tree.setRoot(root);std::cout << "In-order traversal: ";for (auto it = tree.begin(); it.hasNext(); ++it) {std::cout << *it << " ";}std::cout << std::endl;return 0;
}
例子3:STL風格的迭代器適配器
#include <iostream>
#include <vector>
#include <iterator>// 過濾迭代器:只返回滿足條件的元素
template <typename Iterator, typename Predicate>
class FilterIterator {
private:Iterator current;Iterator end;Predicate predicate;void advanceToNextValid() {while (current != end && !predicate(*current)) {++current;}}public:FilterIterator(Iterator begin, Iterator end, Predicate pred): current(begin), end(end), predicate(pred) {advanceToNextValid();}FilterIterator& operator++() {if (current != end) {++current;advanceToNextValid();}return *this;}typename std::iterator_traits<Iterator>::value_type operator*() const {return *current;}bool operator!=(const FilterIterator& other) const {return current != other.current;}bool operator==(const FilterIterator& other) const {return current == other.current;}
};// 輔助函數創建過濾迭代器
template <typename Iterator, typename Predicate>
FilterIterator<Iterator, Predicate> make_filter_iterator(Iterator begin, Iterator end, Predicate pred) {return FilterIterator<Iterator, Predicate>(begin, end, pred);
}int main() {std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};// 定義謂詞:只返回偶數auto isEven = [](int n) { return n % 2 == 0; };std::cout << "Even numbers: ";auto begin = make_filter_iterator(numbers.begin(), numbers.end(), isEven);auto end = make_filter_iterator(numbers.end(), numbers.end(), isEven);for (auto it = begin; it != end; ++it) {std::cout << *it << " ";}std::cout << std::endl;return 0;
}
例子4:支持多種遍歷方式的集合
#include <iostream>
#include <vector>
#include <algorithm>template <typename T>
class CustomCollection {
private:std::vector<T> data;public:void add(const T& item) {data.push_back(item);}// 前向迭代器class ForwardIterator {private:typename std::vector<T>::iterator it;public:explicit ForwardIterator(typename std::vector<T>::iterator iter) : it(iter) {}ForwardIterator& operator++() {++it;return *this;}T& operator*() const {return *it;}bool operator!=(const ForwardIterator& other) const {return it != other.it;}};// 反向迭代器class ReverseIterator {private:typename std::vector<T>::reverse_iterator it;public:explicit ReverseIterator(typename std::vector<T>::reverse_iterator iter) : it(iter) {}ReverseIterator& operator++() {++it;return *this;}T& operator*() const {return *it;}bool operator!=(const ReverseIterator& other) const {return it != other.it;}};ForwardIterator begin() {return ForwardIterator(data.begin());}ForwardIterator end() {return ForwardIterator(data.end());}ReverseIterator rbegin() {return ReverseIterator(data.rbegin());}ReverseIterator rend() {return ReverseIterator(data.rend());}
};int main() {CustomCollection<int> collection;for (int i = 1; i <= 5; ++i) {collection.add(i);}std::cout << "Forward: ";for (auto it = collection.begin(); it != collection.end(); ++it) {std::cout << *it << " ";}std::cout << std::endl;std::cout << "Reverse: ";for (auto it = collection.rbegin(); it != collection.rend(); ++it) {std::cout << *it << " ";}std::cout << std::endl;return 0;
}
總結
迭代器模式是C++中非常重要的設計模式,它:
提供統一的遍歷接口:無論底層數據結構如何,都能使用相同的方式遍歷
支持多種遍歷算法:可以根據需要實現不同的遍歷策略
符合開閉原則:添加新的遍歷方式不需要修改現有代碼
與STL完美集成:C++標準庫大量使用迭代器模式
在實際開發中,迭代器模式常用于:
自定義容器的實現
復雜數據結構的遍歷
數據過濾和轉換操作
提供與STL算法兼容的接口