### Using Cursors to Iterate Over a Collection

Cursor iteration can be done with a for loop. Consider the following example:

    //main.cpp - main file
    #include <iset.h>
    #include <iostream.h>
    #include "person.h"   //person.h from the previous examples

    typedef ISet <Person> AddressList;

    ostream& operator<<(ostream& os,Person A)
    {
        return (os << endl << A.GetPersonName() << " " <<
            A.GetTNumber());
    }

    void main()
    {
        AddressList Business;
        AddressList::Cursor myCursor(Business);
        Person A("Peter Black","714-50706");
        Person B("Carl Render","714-540321");
        Person C("Sandra Summers","x");
        Person D("Mike Summers","x");
        Person E;
        Business.add(A);
        Business.add(B);
        Business.add(C);
        Business.add(D);

        //List of all elements in the set
        for (myCursor.setToFirst();
            myCursor.isValid();
            myCursor.setToNext())
        {
            cout << Business.elementAt(myCursor);
        }
    }

AddressList::Cursor is the Cursor class that is nested within the class AddressList. Its constructor takes a Business object as an argument. The name of the cursor object in the example above is myCursor.

The Collection Classes define a macro forICursor that lets you write a cursor iteration even more elegantly:

    #define forICursor(c)      \
        for ((c).setToFirst(); \
            (c).isValid();     \
            (c).setToNext())

Use it like this:

    forICursor(myCursor) {
        cout << Business.elementAt(myCursor);
    }

If the element is used read-only, a function of the cursor can be used instead of elementAt(myCursor):

    forICursor(myCursor) {
        cout << myCursor.element();   //myCursor is associated to Business
    }

The function element above is a function of the Cursor class. It returns a const reference to the element currently pointed at by the cursor. The element returned might therefore not be modified. Otherwise it would be possible to manipulate a constant collection by using cursors.

Note: To remove multiple elements from a collection, use the removeAll function with a predicate function as an argument. Using cursor iteration to identify the elements to remove causes the first element removed to invalidate the cursor.

Introduction to the Collection Classes
Collection Characteristics
Overview of Iteration
Iteration with Cursors

Adding an Element to a Collection
Removing an Element from a Collection
Using Cursors to Locate and Access Elements
Using allElementsDo and Applicators to Iterate Over a Collection
Cursors vs. Exception Handling
Instantiating the Collection Classes
Troubleshooting Problems while Using the Collection Class Library