5 Iterator

Sometimes it is useful to have an ``iterator'' for traversing a container. An iterator typically has the following interfaces: initialization, next, comparison and end.

In our case, we can add a public iterator class into the BArray class:

class iterator
{
    BArray *array;
    unsigned pos;
  public:
    iterator(BArray &who, unsigned pos);
    iterator(void);
    bool operator == (const iterator &v);
    Lv operator *(void);
    void operator ++(int);
};

The methods are implemented as follows:

The constructor is just an initializer:

BArray::iterator(BArray &who, unsigned p):array(&who),pos(p)
{
}

BArray::iterator(void)
{
}

The equality operator checks to make sure the array and position are both the same:

bool BArray::iterator::operator == (const BArray::iterator &v)
{
  return (array == v.array) && (pos == v.pos);
}

The dereference operator returns the value of a position in the array:

BArray::Lv BArray::iterator::operator *(void)
{
  return Lv(*array, pos);
}

The increment operator increments the iterator position.

void BArray::iterator::operator ++(int)
{
  pos++;
}

We also need to add a few iterator creation methods in BArray:

BArray::iterator BArray::begin(void)
{
  return iterator(*this, 0);
}

BArray::iterator BArray:end(void)
{
  return iterator(*this, size);
}

With these definitions, we can now write a loop to iterate through a BArray as follows:

{
  BArray ba[20];

  BArray::iterator i;

  for (i = ba.begin(); i != ba.end(); i++) 
  {
    cout << *i << endl;
  }
}


Copyright © 2006-09-28 by Tak Auyeung