c ++ iterator function classification

Functional classification iterator

Iterator different containers, the strength of its function differently. Iterator function of the strength of the container, the container determines whether an algorithm supports STL. For example, sorting algorithms need to access elements in a container through a random access iterators, so some of the container does not support sorting algorithms.

Common iterator function strength divided by the input, output, forward, bidirectional, random access five kinds of commonly used here only three.

1) Forward iterators. Let p be a forward iterator, then p supports the following operations: ++ p, p ++, * p. In addition, two forward iterator can be assigned to each other, can also be used ==and !=operators for comparison.

2) bidirectional iterators. Bidirectional iterator has all the functionality of a forward iterator. In addition, if p is a bidirectional iterator, then --pand p--are all defined. --pP and towards such ++popposite direction of movement.

3) random access iterators. Random access iterator has all the functionality of bidirectional iterators. If p is a random access iterators, i is an integer variable or constant, then p also supports the following operations:

  • p + = i: p is moved backward so that the i-th element.
  • p- = i: p such that i elements move forward.
  • p + i: p returns an iterator behind the i-th element.
  • pi: p returns an iterator front of the i-th element.
  • p [i]: p after the return of the i-th element of reference.


In addition, two random access iterators p1, p2 can also use <,>, <=,> = operator compared. p1<p2The meaning: p1 after several (at least once) ++after the operation, will be equal to p2. Other meanings comparative approach is similar.

For two random access iterators p1, p2, expression p2-p1is also defined, whose value is the difference between the return element and the number of points p1 and p2 pointed elements (number of elements can be said Save between p1 and p2 One).

Table different containers iterator functions shown in FIG.

Table 1: iterator functions different containers
container Iterator function
vector Random access
and Random access
list Two-way
set / multiset Two-way
map / multimap Two-way
stack Does not support iterators
queue Does not support iterators
priority_queue Does not support iterators


For example, random vector iterator iterators, and therefore traverse the vector container are the following approach. The following program, each cycle demonstrated an approach.

Guess you like

Origin www.cnblogs.com/cqu-qxl/p/11511737.html