在 C++11 之后,范围-based for 循环(range‑based for loop)为遍历容器提供了极大便利。
如果你想让自己的自定义容器(例如一个二维数组、图的邻接表、或者一个特殊的缓存结构)也能被范围‑for 语法直接遍历,
就需要实现一个符合迭代器要求的内部迭代器类型,并为容器提供 begin() 与 end() 成员函数。
下面我们以实现一个简单的二维矩阵类为例,演示如何完整地实现自定义迭代器并让其支持范围‑for。
1. 目标
实现一个 `Matrix
` 类,内部使用 `std::vector>` 存储数据,并提供: – 访问与修改元素的方法 – 行列数查询 – **自定义迭代器**,支持从左到右、从上到下的行优先遍历 – `begin()`、`end()` 成员,使得 `for (auto val : matrix)` 能正常工作 ### 2. 基本结构 “`cpp template class Matrix { public: Matrix(size_t rows, size_t cols, const T& init = T{}) : rows_(rows), cols_(cols), data_(rows, std::vector (cols, init)) {} T& at(size_t r, size_t c) { return data_[r][c]; } const T& at(size_t r, size_t c) const { return data_[r][c]; } size_t rows() const { return rows_; } size_t cols() const { return cols_; } // 下面是迭代器相关 class iterator; iterator begin() { return iterator(*this, 0); } iterator end() { return iterator(*this, rows_ * cols_); } private: size_t rows_, cols_; std::vector> data_; }; “` ### 3. 迭代器实现 迭代器需要满足 InputIterator 的基本接口,最简洁的做法是: – 记录当前线性索引 `idx`(从 0 开始,最大为 `rows*cols`) – 通过索引映射到二维坐标:`row = idx / cols_`,`col = idx % cols_` – 重载 `operator*()`、`operator++()`、`operator==/!=` “`cpp template class Matrix ::iterator { public: // 构造函数 iterator(Matrix & matrix, size_t idx) : matrix_(matrix), idx_(idx) {} // 解引用,返回当前元素引用 T& operator*() { size_t r = idx_ / matrix_.cols_; size_t c = idx_ % matrix_.cols_; return matrix_.data_[r][c]; } // 前置递增 iterator& operator++() { ++idx_; return *this; } // 后置递增 iterator operator++(int) { iterator tmp = *this; ++(*this); return tmp; } // 相等比较 bool operator==(const iterator& other) const { return idx_ == other.idx_; } bool operator!=(const iterator& other) const { return !(*this == other); } private: Matrix & matrix_; size_t idx_; }; “` > **注意**:为了让迭代器返回引用,`operator*()` 必须返回 `T&`。如果你想支持常量遍历,需要再定义一个 `const_iterator`。 ### 4. 让 const Matrix 也支持遍历 “`cpp class const_iterator { public: const_iterator(const Matrix & matrix, size_t idx) : matrix_(matrix), idx_(idx) {} const T& operator*() const { size_t r = idx_ / matrix_.cols_; size_t c = idx_ % matrix_.cols_; return matrix_.data_[r][c]; } const_iterator& operator++() { ++idx_; return *this; } const_iterator operator++(int) { const_iterator tmp = *this; ++(*this); return tmp; } bool operator==(const const_iterator& other) const { return idx_ == other.idx_; } bool operator!=(const const_iterator& other) const { return !(*this == other); } private: const Matrix & matrix_; size_t idx_; }; const_iterator begin() const { return const_iterator(*this, 0); } const_iterator end() const { return const_iterator(*this, rows_ * cols_); } “` ### 5. 使用示例 “`cpp int main() { Matrix m(3, 4, 0); // 填充矩阵 for (size_t i = 0; i (i * 10 + j); // 通过范围 for 遍历 std::cout & cm = m; for (const auto& val : cm) std::cout