迭代器是C++ STL中用于遍历容器元素的通用机制,其行为类似指针,支持解引用、自增等操作。不同容器提供不同类型迭代器:vector支持随机访问迭代器,list为双向迭代器,map迭代器指向键值对,需通过first和second访问键值。常见操作包括begin()、end()、*it、++it等。使用时需避免失效迭代器、不越界解引用,并推荐使用auto简化声明,掌握迭代器是理解STL的关键。

在C++中,迭代器(iterator)是用于遍历容器元素的一种通用机制。它类似于指针,可以指向容器中的某个元素,并通过自增、解引用等操作访问数据。使用迭代器可以让算法与具体容器类型解耦,提高代码的通用性和可维护性。
迭代器是一种对象,它提供了一种统一的方式来访问标准模板库(STL)容器中的元素,比如 vector、list、set、map 等。每种容器都定义了自己的迭代器类型,但使用方式基本一致。
常见的迭代器操作包括:
以下是一些常用容器中迭代器的基本用法。
立即学习“C++免费学习笔记(深入)”;
1. vector 的迭代器vector 支持随机访问迭代器,可以高效地进行遍历和随机访问。
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
// 使用迭代器遍历
for (auto it = vec.begin(); it != vec.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}
1 2 3 4 5
2. list 的迭代器
list 是双向链表,支持双向迭代器。
#include <iostream>
#include <list>
using namespace std;
int main() {
list<string> names = {"Alice", "Bob", "Charlie"};
for (auto it = names.begin(); it != names.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}
Alice Bob Charlie
3. map 的迭代器
map 的迭代器指向的是键值对(pair),需要用 first 和 second 访问。
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, string> student = {{101, "Tom"}, {102, "Jerry"}};
for (auto it = student.begin(); it != student.end(); ++it) {
cout << "ID: " << it->first
<< ", Name: " << it->second << endl;
}
return 0;
}
ID: 101, Name: Tom<br>ID: 102, Name: Jerry
C++ 中根据功能强弱将迭代器分为五类:
不同容器提供的迭代器类型不同,决定了能执行的操作范围。
使用迭代器时要注意以下几点:
auto it = vec.begin();
基本上就这些。掌握迭代器的使用是学习 STL 的关键一步,理解其原理有助于写出更通用、高效的 C++ 代码。
以上就是c++++中iterator迭代器怎么用_iterator迭代器使用详解的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号