STL——迭代器

迭代器:

头文件<iterator>

提供一种方法顺序访问一个聚合对象中各个元素。能够让容器和算法不干扰的相互发展,最后又能黏合起来。

每种容器都有自己的迭代器类型。

按照STL中的分类,iterator包括:

1、输入迭代器,input iterator:可以被复制构造和赋值,可以自增,可以做相等性和不相等性的比较,可做右值引用。

2、输出迭代器,output iterator:包括输入迭代器的所有功能,并能作为左值。

3、前向迭代器,forward iterator:包括输出迭代器所有功能,并能默认构造。

4、双向迭代器:包括前向迭代器所有功能,并能自减。

5、随机存取迭代器:包括双向迭代器所有功能,支持,关系运算 < <= > >= , 组合赋值 += -= ,算术运算 + - ,下标运算 []

STL——迭代器

category characteristic valid expressions
all categories Can be copied and copy-constructed X b(a);
b = a;
Can be incremented ++a
a++
*a++
Random Access Bidirectional Forward Input Accepts equality/inequality comparisons a == b
a != b
Can be dereferenced as an rvalue *a
a->m
Output Can be dereferenced to be the left side of an assignment operation *a = t
*a++ = t
  Can be default-constructed X a;
X()
  Can be decremented --a
a--
*a--
  Supports arithmetic operators + and - a + n
n + a
a - n
a - b
Supports inequality comparisons (<><= and >=) between iterators a < b
a > b
a <= b
a >= b
Supports compound assignment operations += and -= a += n
a -= n
Supports offset dereference operator ([]) a[n]

针对不同的容器提供了不同类型的迭代器:


迭代器类型 描述 提供者 标签Tag
输入(Input) 通过前移操作读取数据。 这种迭代器可以前移,可以比较,也可以解除引用。 istream input_iterator_tag
输出(Output) 通过前移动作写入数据。 这种迭代器可以前移,也可以解除引用。 ostream, inserter output_iterator_tag
前向(Forward) 通过前移操作读写数据。结合了输入迭代器和输出迭代器的功能,能够存储迭代器的值。 slist forward_iterator_tag
双向(Bidirectional) 通过前移操作和后移操作读写数据。这些迭代器类似于前向迭代器,但是,可以对其进行前移或者后移。 list, map, multimap, set, multiset bidirectional_iterator_tag
随机存取(Random-access) 随机读写数据,是功能最强的迭代器,结合了双向迭代器的功能,能够进行指针算术运算和指针比较运算。 array, deque, string, vector random_access_iterator_tag

每种容器都有iterator,const_iterator,至于所属类型要根据具体容器类型决定。

迭代器定义如下:

STL——迭代器

    value_type: 代表迭代器所指对象的类型。

  difference_type:代表两个迭代器之间的距离

  reference_type:代表迭代器所指对象的引用类型。简言之,它是operator*()的返回类型

  pointer_type:代表迭代器所致对象的指针类型。简言之,它是operator->()的返回类型

  iterator_category:代表1中提出的五种迭代器的类型标识