迭代器是C++ STL中用于统一访问容器元素的对象,支持begin()和end()遍历,可应用于vector、list、map等容器,结合auto和范围for循环提升代码安全与简洁性。

在C++中,迭代器(Iterator)是STL(标准模板库)中用于遍历容器元素的重要工具。它类似于指针,可以指向容器中的某个元素,并通过递增或递减来访问其他元素。使用迭代器可以统一不同容器的访问方式,提高代码的通用性和可维护性。
迭代器是一种对象,它允许程序员以相同的方式访问不同类型的STL容器(如 vector、list、set、map 等),而无需关心容器内部的具体实现。每个支持迭代器的容器都提供了以下两个关键成员函数:
通过从 begin() 到 end() 的遍历,可以访问容器中的所有元素。
下面展示几种常用STL容器中迭代器的基本使用方式。
立即学习“C++免费学习笔记(深入)”;
1. 使用 vector 的迭代器vector 是动态数组,支持随机访问迭代器。
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> nums = {1, 2, 3, 4, 5};
// 使用迭代器遍历
for (auto it = nums.begin(); it != nums.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}
list 是双向链表,也支持双向迭代器。
#include <list>
#include <iostream>
using namespace std;
int main() {
list<string> words = {"hello", "world", "STL"};
for (auto it = words.begin(); it != words.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}
map 是关联容器,存储键值对,迭代器指向 pair 类型元素。
#include <map>
#include <iostream>
using namespace std;
int main() {
map<string, int> ages;
ages["Alice"] = 25;
ages["Bob"] = 30;
for (auto it = ages.begin(); it != ages.end(); ++it) {
cout << it->first << ": " << it->second << endl;
}
return 0;
}
如果只是读取容器内容而不修改,建议使用 const_iterator 或 const auto& 来保证安全性。
现代C++推荐写法:
// 推荐方式:简洁且安全
for (const auto& elem : container) {
cout << elem << " ";
}
// 或使用 auto it 遍历
for (auto it = container.begin(); it != container.end(); ++it) {
// ...
}
STL还提供反向迭代器,用于从后往前遍历。
示例:
vector<int> nums = {1, 2, 3, 4, 5};
for (auto rit = nums.rbegin(); rit != nums.rend(); ++rit) {
cout << *rit << " ";
}
// 输出:5 4 3 2 1
基本上就这些。掌握 begin/end、auto 推导和范围 for 循环,就能高效使用C++迭代器。注意不要对 end() 迭代器解引用,也不要在遍历时随意插入/删除元素(除非使用支持的安全方法)。
以上就是C++如何使用迭代器_C++ STL容器遍历器(Iterator)的基本用法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号