Skip to main content

8.2) Using Iterators To Access Containers (cont'd)


  • Iterators act like 'pointers' to an element of a container
  • An iterator can be incremented or decremented to move it forward or backward through a container; typically, we do this in a for loop
  • An iterator can be 'dereferenced' using * to access the element to which it points (this same syntax is used by pointers, covered later)
  • All containers have methods called begin and end that return iterators bounding the container: begin returns an iterator pointing to the first element and end returns an iterator pointing just past the last element
  • Each container has several types of iterator associated with it: as a minimum, there will be an iterator type that can be used to both read from and write to elements in the container and a const_iterator type that provides read-only access
  • Iterators give C++ the means to provide a library of generic algorithms that can operate on many different types of containers (see later)