Iterator:
Def:An iterator is any object that, pointing to someelement in a range of elements (such as an array or a container), has the ability to iterate through theelements of that range using a set of operators (with at least the increment (++
) and dereference (*
) operators).
最常见的iterator就是指针;实际上是指针概念的泛型化,它指向容器中的元素,能像指针一样增减,Iterator可以说是面向对象版本的指针,当然也包括指针本身。
Iterator的作用就是把算法与容器连接起来,算法指示间接的通过Iterator操作容器中的元素,算法本身与容器无关,所以说Iterator真的真的很强大,有木有。
迭代器根据其实现的功能分为五类:
Input
Input and output iterators are themost limited types of iterators: they can perform sequential single-pass inputor output operations.
Forward iterators (读写)have all the functionality of input iterators(只读) and -if they are not constant iterators-also the functionality of output iterators(只写), although they are limited to one direction in which toiterate through a range (forward). All standard containers supportat least forward iterator types.
Bidirectional iterators(读写) are like forward iterators butcan also be iterated through backwards.
Random-access iterators(读写) implement all the functionality of bidirectional iterators, and also have the ability to access rangesnon-sequentially: distant elements can be accessed directly by applying anoffset value to an iterator without iterating through all the elements inbetween. These iterators have a similar functionality to standard pointers(pointers are iterators of this category).
The properties of each iterator category are:
category | properties | valid expressions | |||
all categories | X b(a); | ||||
Can be incremented | ++a | ||||
Supports equality/inequality comparisons | a == b | ||||
Can be dereferenced as an rvalue | *a | ||||
Can be dereferenced as an lvalue | *a = t | ||||
X a; | |||||
Multi-pass: neither dereferencing nor incrementing affects dereferenceability | { b=a; *a++; *b; } | ||||
Can be decremented | --a | ||||
Supports arithmetic operators + and - | a + n | ||||
Supports inequality comparisons (<, >, <= and >=) between iterators | a < b | ||||
Supports compound assignment operations += and -= | a += n | ||||
Supports offset dereference operator ([]) | a[n] |
总结:
迭代器是指针的泛化,它从这些指针的要求中抽象出来,允许 C++ 程序使用统一的方式来处理不同的数据结构。迭代器充当容器和泛型算法之间的媒介。算法被定义为对某一迭代器类型所指定的范围起作用,而不是作用于特定的数据类型。随后,算法可能会作用于任何满足迭代器要求的数据结构。迭代器有五个类型或类别,各自具有自己的要求和最终功能:
输出:向前移动,可以存储但不能检索值,由ostream 和 inserter 提供。
输入:向前移动,可以检索但不能存储值,由istream 提供。
向前:向前移动,可以存储和检索值。
双向:向前和向后移动,可以存储和检索值,由列表、集合、多重集、映射和多重映射提供。
随机访问:以任意顺序访问元素,可以存储和检索值,由向量、双端队列、字符串和数组提供。
可使用要求较高、因而需要更强大元素访问的迭代器来代替要求较低的迭代器。 例如,如果调用向前迭代器,则可使用随机访问迭代器来代替。