容器就是数据结构的泛指,迭代器就是指针的泛指,可以指向元素。容器相当于一个储藏柜,里面装的许多不同的物品就像是储存的元素,比如面包、啤酒、苹果、现金。要取得各个物体就得用与各个物体向匹配的工具,如取出面包要用盘子、取出啤酒要用杯子、取出苹果要用篮子、取出现金要用钱包。迭代器的作用就相当于取出物品的工具的抽象,通过迭代器泛指现实生活中从贮藏室中取出物体的工具。C++迭代器是一种检查容器内元素并遍历元素的数据类型。1 Iterator definitionsIn C++, an iterator is any object that, pointing to some element in a range of elements (such as an array or a container), has the ability to iterate through the elements of that range using a set of operators (at least, the increment (++) and dereference (*) operators).
The most obvious form of iterator is a pointer: A pointer can point to elements in an array, and can iterate through them using the increment operator (++). But other forms of iterators exist. For example, each container type (such as a vector) has a specific iterator type designed to iterate through its elements in an efficient way.C++迭代器Interator就是一个指向某种STL对象的指针。通过该指针可以简单方便地遍历所有元素。 C++中的iterator为STL中的重要概念。iterator的概念源自于对遍历一个线性容器工具的抽象,即如何你能访问这个容器的某个元素。对于最简单的数组,当然可以用数组的索引值,因为数组是连续存放在内存中的;但对于链表,就必须用指针。除此之外,还有还有很多种数据结构需要提供一个方便的工具来访问其中的元素,方法有ID,关键字等等。为了统一所有的容器的这种工具的使用,一般提供一整套容器的开发者就会用一种方式来表示各种容器的访问工具。例如C++ STL就是使用iterator。MFC自己的容器使用position。C#和java也有自己的方法,但方法是不变的。 iterator的用法可以被统一,但不同的底层容器实现其iterator的原理是不一样的。例如iterator++你可以理解为移动到容器的下一个元素,如果底层如果是数组,把索引值加一就行;如果底层是链表,就得执行类似于m_pCurrent = m_pCurrent-> pNext;的操作。因此每种容器都有自己的iterator实现方法。
C++ STL iterator的常用方法有:
iterator++ 移到下个元素
iterator-- 移到上个元素
*iterator 访问iterator所指元素的值
< > == != iterator之间的比较,例如判断哪个元素在前
iterator1 + iterator2 iterator之间的加法运算,类似于指针加法 2 容器的 iterator 类型每种容器类型都定义了自己的C++迭代器类型,如 vector:vector