Iterators are usually a sort of smart pointer with a bunch of operators overloaded, including the * operator. As I mentioned earlier, iterators are linked to the container class they iterate on. That is why they are declared within the container class.
Iterators in STL are linked to the containers that they iterate on. That is, a vector iterator is declared as something like:
vector
© Nachum Danzig 2011
An iterator is used to move thru the elements an STL container (vector, list, set, map, ...) in a similar way to array indexes or pointers. The * operator dereferences an iterator (ie, is used to access the element an iterator points to) , and ++ (and -- for most iterators) increments to the next element.
Iterating over a vector with subscripts
Passing over all the elements of a vector is simple, and is usually done using subscripts instead of an iterator. The main advantage of an iterator is that it can be used by many of the functions in the header <algorithms>.
Subscripts provide an easy, familiar way to access vector elements in much the way that array elements would be accessed.
//--- Iterating over vector with subscript.
vector
Operation Effect
c.insert(pos,elem) Inserts at iterator position pos a copy of elem and returns the position of the new element
c.insert(pos,n,elem) Inserts at iterator position pos n copies of elem (returns nothing)
c.insert(pos,beg,end) Inserts at iterator position pos a copy of all elements of the range [beg,end) (returns nothing)
c.push_back(elem) Appends a copy of elem at the end
c.pop_back() Removes the last element (does not return it)
c.erase(pos) Removes the element at iterator position pos and returns the position of the next element
c.erase(beg,end) Removes all elements of the range [beg,end) and returns the position of the next element
c.resize(num) Changes the number of elements to num (if size() grows, new elements are created by their default constructor)
c.resize(num,elem) Changes the number of elements to num (if size() grows, new elements are copies of elem)
c.clear() Removes all elements (makes the container empty)