STL#2

来源:互联网 发布:手机耳机话筒检测软件 编辑:程序博客网 时间:2024/05/21 20:29

这里介绍Iterators(迭代器), 也就是STL四个组件之一。

迭代器的作用类似指针。 但不是指针, 而是类对象。 可以理解为一个泛型指针。 迭代器主要用于访问容器的元素。 迭代器经常用于遍历容器内的元素。 该过程被称为容器内的元素迭代访问。

迭代器总共有五种, 如下:

(1)input iterators(输入迭代器): 只能用于读取容器内的a sequence of values 。

(2) output iterators(输出迭代器): 只能用于向容器内write a sequence of values。

(3) forward iterators (前向迭代器):该迭代器可以can be read, written to, and move forward。

(4)bidirectional iterators(双向迭代器): 可以向 forward iterators用, 但是该迭代器最大的特点是可以 move backwards(这就是为什么叫做双向迭代器的)

 

注意上述的四种迭代器的访问容器的方法是线性的。 而迭代器(5)却是随机的, 是非线性的。

(5) random access iterators (随机存取迭代器): 访问方法是随机的, 可以读写容器内的元素。 也就是说可以一次可以move freely any number of steps。

 

双向迭代器既能向前移动, 也能向后移动。 随机访问迭代器结合了双向迭代器的功能, 可以转到容器的任意位置。

It is possible to have bidirectional iterators act like random access iterators, as moving forward ten steps could be done by simply moving forward a step at a time a total of ten times. However, having distinct random access iterators offers efficiency advantages. For example, a vector would have a random access iterator, but a list only a bidirectional iterator。

不同类型的迭代器必须用于不同类型的容器。 注意到, 只有线性和关联式容器才能用于迭代器遍历, 衍生容器不能用迭代器。  如下图:

 

 

迭代器的好处就是把容器和算法有机结合起来了。  每一种容器型别都必须提供自己的迭代器。事实上每一种容器都将其迭代器以嵌套的方式定义于内部。因此各种迭代器的接口相同,型号却不同。这直接导出了泛型程序设计的概念:所有操作行为都使用相同接口,虽然它们的型别不同。

This generality also comes at a price at times. For example, performing a search on an associative container such as a map or set can be much slower using iterators than by calling member functions offered by the container itself. This is because an associative container's methods can take advantage of knowledge of the internal structure, which is opaque to algorithms using iterators.

 

 

 

0 0