Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Iterator

 

Iterators allow a uniform way to travel through all STL containers.

 

#include <iostream>
#include <list>

int main()
{
  std::list<int> my_list;
  my_list.push_back( 1);
  my_list.push_back( 4);
  my_list.push_back( 9);
  my_list.push_back(16);
  my_list.push_back(25);
  my_list.push_back(36);
  my_list.push_back(49);

  //Display the list (not preferred)
  typedef std::list<int>::const_iterator Iterator;
  const Iterator j = my_list.end();
  for (Iterator i = my_list.begin(); i!=j; ++i)
  {
    std::cout << *i << '\n';
  }
}

 

Screen output:

 

1
4
9
16
25
36
49

 

Note the following about the code shown above:

  1. The preferred way to display the contents of the list can be found at the CoutContainer code snippet. Prefer using standard algorithms, instead of crafting your own for loops [1].
  2. std::list<int>::const_iterator was used, instead of std::list<int>::iterator. Use const_iterator when you are not modifying the contents of a container [2].
  3. operator!= was used instead of operator<. Prefer comparing iterators with operator!=, instead of operator< [3].
  4. The prefix form of operator++ was used (that is '++i' instead of 'i++'). Prefer using the prefix form, unless you really need the old value [4].

 

 

 

 

 

References

 

  1. Herb Sutter. Exceptional C++ style. 2005. ISBN: 0-201-76042-8. Item 1 guideline: 'Prefer reusing algorithms, particularly standard algorithms (e.g., for_each), instead of crafting your own loops'.
  2. Herb Sutter. Exceptional C++ style. 2005. ISBN: 0-201-76042-8. Item 1 guideline: 'Use const_iterator when you are not modifying the contents of a container'.
  3. Herb Sutter. Exceptional C++ style. 2005. ISBN: 0-201-76042-8. Item 1 guideline: 'Prefer comparing iterators with !=, not <'.
  4. Herb Sutter. Exceptional C++ style. 2005. ISBN: 0-201-76042-8. Item 1 guideline: 'Get in the habit of using the prefix forms of -- and ++ by default, unless you really need the old value'.

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict