迭代器:一种抽象的设计概念,在设计模式中有迭代器模式,即提供一种方法,使之能够依序寻访某个容器所含的各个元素,而无需暴露该容器的内部表述方式。迭代器只是一种概念上的抽象,具有迭代器通用功能和方法的对象都可以叫做迭代器。迭代器有很多不同的能力,可以把抽象容器和通用算法有机的统一起来。迭代器基本分为五种,输入输出迭代器,前向逆向迭代器,双向迭代器和随机迭代器。
在 C++ STL 中,容器 vector、deque 提供随机访问迭代器,list 提供双向迭代器,set 和 map 提供向前迭代器。
使用迭代器的优点:
程序实例:
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
vector<int>::iterator iter = arr.begin(); // 定义迭代器
for (; iter != arr.end(); ++iter)
{
cout << *iter << " ";
}
return 0;
}
/*
运行结果:
1 2 3 4 5 6 7 8 9 0
*/
阅读量:681
点赞量:0
收藏量:0