STL Iterators

Summary of Chapter 33 STL Iterators from The C++ Programming Language 4th. Ed., Bjarne Stroustrup.

-------------------------------------------------------------------------------------------------------------------------------------------------

The reason that STL containers and algorithms work so well together is that they now nothing of each other.

                                          -- Alex Stepanov

Iterators are the glue that ties standard-library algorithms to their data. Conversely, you can say that iterators are the mechanism used to minimize an algorithm's dependence on the data structures on which it operates:

 

Iterator Model

An iterator is akin to a pointer in that it provides operations for indirect access (e.g., * for dereferencing) and for moving to point to a new element (e.g., ++ for moving to the next element).

 

Iterator Categories

The standard library provides five kinds of iterators (five iterator categories):

  • Input iterator: We can iterate forward using ++ and read each element (repeatedly) using *. We can compare input interators using == and !=. This is the kind of iterator that istream offers;
  • Output iterator: We can iterate forward using ++ and write an element once only using *. That is the kind of iterator that ostream offers;
  • Forward iterator: We can iterate forward repeatedly using ++ and read and write (unless the elements are const) elements repeatedly using *. If a forward iterator points to a class object, we can use -> to refer to a member. We can compare forward iterators using == and !=. This is the kind of iterator forward_list offers.
  • Bidirectional iterator: We can iterate forward (using ++) and backward (using --) and read and write (unless the elements are const) elements repeatedly using *. If a bidirectional iterator points to a class object, we can use -> to refer to a member. We can compare bidirectional iterators using == and !=. This is the kind of iterator that list, map, and set offer.
  • Random-access iterator; we can iterate forward (using ++ or +=) and backward (using - or -=) and read and write (unless the elements are const) elements repeatedly using * or []. If a random-access iterator points to a class object, we can use -> to refer to a member. We can subscript a random-access iterator using [], add an integer using + and subtract an iteger using -. We can find the distance between two random-acess iterators to the same sequence by subtracting one from the other. We can compare random-access iterators using ==, !=, <, <=, >, and >=. This is the kind of iterator that vector offres.

If you need to do something advanced with iterator categories, use iterator_traints (directly or indirectly).

 

posted @ 2016-03-23 19:53  Pat  阅读(168)  评论(0编辑  收藏  举报