Cpp Iterator
Table of Contents

Introduction

An iterator is an object that, pointing to some element in a range of elements has the ability to iterate through the elements of that range using a set of operators.

+Categories

Input: Only sequential input operations.
Output: Only sequential input operations.
Forward: Have all the functionality of Input and Output but are limited to one direction.
Bidirectional: Can be iterated through in both directions.
RandomAccess: All the functionalities of bidirectional iterators, plus they can access ranges non-sequentially.

Examples

Example 1: Simple iterator that traverse through an array.

// iterator example
#include <iostream>
#include <iterator>
using namespace std;
 
class myiterator : public iterator<input_iterator_tag, int>
{
  int* p;
public:
  myiterator(int* x) :p(x) {}
  myiterator(const myiterator& mit) : p(mit.p) {}
  myiterator& operator++() {++p;return *this;}
  myiterator& operator++(int) {myiterator tmp(*this); operator++(); return tmp;}
  bool operator==(const myiterator& rhs) {return p==rhs.p;}
  bool operator!=(const myiterator& rhs) {return p!=rhs.p;}
  int& operator*() {return *p;}
};
 
int main () {
  int numbers[]={10,20,30,40,50};
  myiterator beginning(numbers);
  myiterator end(numbers+5);
  for (myiterator it=beginning; it!=end; it++)
      cout << *it << " ";
  cout << endl;
 
  return 0;
}

Example 2: Not-so-common iterator mistakes. The following code has four iterator-related problems.

int main() 
{
  vector<Date> e;
  copy( istream_iterator<Date>( cin ),
        istream_iterator<Date>(),
        back_inserter( e ) );
  vector<Date>::iterator first =
        find( e.begin(), e.end(), "01/01/95" );
  vector<Date>::iterator last =
        find( e.begin(), e.end(), "12/31/95" );
  *last = "12/30/95";
  copy( first,
        last,
        ostream_iterator<Date>( cout, "\n" ) );
  e.insert( --e.end(), TodaysDate() );
  copy( first,
        last,
        ostream_iterator<Date>( cout, "\n" ) );
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.