iterator
🚀 概述¶
迭代器(iterator)是 STL 容器的重要组成部分,它类似于一个 智能指针,可以用来 遍历容器中的元素。
所有 STL 容器(如 vector
, list
, set
, map
等)都提供了对应的迭代器类型,使得容器的使用更加灵活和统一。
💡 作用:
- 统一容器访问方式
- 与算法(如
sort
,find
,lower_bound
等)配合使用 - 实现抽象的数据访问
🧰 常见迭代器种类¶
类型 | 示例 | 描述 |
---|---|---|
普通迭代器 | vector<int>::iterator |
可读可写,可向前移动 |
常量迭代器 | vector<int>::const_iterator |
只读,可向前移动 |
反向迭代器 | vector<int>::reverse_iterator |
从尾到头迭代 |
常量反向迭代器 | vector<int>::const_reverse_iterator |
从尾到头,只读 |
📝 C++11 起支持 auto 声明迭代器,如:
for (auto it = v.begin(); it != v.end(); ++it)
🔁 基本使用方式¶
以 vector<int> v
为例:
for (vector<int>::iterator it = v.begin(); it != v.end(); ++it)
{
cout << *it << " ";
}
🌟 使用 auto
简化写法:
for (auto it = v.begin(); it != v.end(); ++it)
{
cout << *it << " ";
}
📌 解引用 *it
获取元素值;使用 ++it
移动到下一个元素。
🧩 常用函数与操作¶
功能 | 示例 | 描述 |
---|---|---|
获取起始迭代器 | v.begin() / v.end() |
指向第一个 / 尾后元素 |
反向迭代器 | v.rbegin() / v.rend() |
反向迭代起点 / 终点 |
只读迭代器 | v.cbegin() / v.cend() |
常量迭代器(不能修改元素) |
解引用 | *it |
获取迭代器指向的元素值 |
成员访问 | it->属性 (如 pair) |
访问结构体/类成员 |
移动迭代器 | ++it , --it |
前/后移动迭代器 |
💡 与算法结合使用¶
vector<int> v = {4, 1, 3, 5};
sort(v.begin(), v.end()); // 升序排序 1, 3, 4, 5
auto it = lower_bond(v.begin(), v.end(), 2); // 查找大于等于 2 的元素
if (it != v.end()) cout << "Found";
else cout << *it; // 会输出 3
🔍 迭代器常用于 lower_bound
, upper_bound
, find_if
, count
等 STL 算法中。
🔒 const_iterator 的用途¶
当你不希望容器内容被修改时使用 const_iterator
:
for (vector<int>::const_iterator it = v.cbegin(); it != v.cend(); ++it)
{
cout << *it << endl; // 只读
}
🔐 可以防止误操作修改元素。
🔄 反向迭代器¶
有些场景需从后往前遍历,可用 rbegin()
和 rend()
:
for (auto rit = v.rbegin(); rit != v.rend(); ++rit)
{
cout << *rit << " ";
}
📚 总结¶
类型 | 可读 | 可写 | 方向 |
---|---|---|---|
iterator | ✅ | ✅ | 正向 |
const_iterator | ✅ | ❌ | 正向 |
reverse_iterator | ✅ | ✅ | 反向 |
const_reverse_iterator | ✅ | ❌ | 反向 |
✅ 推荐习惯性使用 auto
简化代码
✅ 熟练掌握迭代器是深入 STL 编程的基础
🧠 典型应用场景:¶
- 配合算法遍历容器 (
sort
,find
,count
, ...) - 对
map
,set
等不支持下标的容器进行访问 - 实现统一遍历接口,无需关注容器底层结构