Resources‎ > ‎Programming‎ > ‎C++‎ > ‎C++ Tutorial‎ > ‎

Lesson 8

Practice 1 (Iterator Design Pattern)

When you have an array (such as int[]), you can use a for loop to go through the array and access each element in the array:

for (int i = 0; i < n; i++) {
    ...
    myArray[i] = i * i;
    ...
}

If you have a more complex data structure such as linked list, you might do the similar looping like:

SomeData *p;
for (p = list.head; p != NULL; p = p->next) {
    ...
    p->value ...;
    ...
}

This commonly used statement is generalised as "Iterator Pattern". In order to design this behaviour, you would need to be able to obtain begin()end() and next() from a given data structure (collection-like structures like array, list, etc).

Step 1

For this practice, first implement a class called IntObject to store an integer value. The class should have:

  • a constructor(s), destructor(s),
  • set/get functions.
class IntObject{
    .... // implement here
}

Step 2

Next, implement a class which holds a specified number of IntObject objects. The constructor should create an array of IntObject with the specified size. The constructor should set the index of each IntObject as its integer value.

class IntObjectArray{
    int size;
    IntObject *data;
public:
    ...
}

This class should also implement a function to return the size of the array and to get an IntObject of the specified index:

    int size() {...}
    IntObject * get(int index) {...}

Step 3

Now, we create an iterator for IntObjectArray in order to access each IntObject in the array. This class should hold a pointer to IntObjectArray and the index of the currently visited element. This class also has begin()end()current()next(), and prev() to access each and all elements in the array.

class IntObjectIterator {
    IntObjectArray *obj;
    int  d_current;
public:
    IntObjectIterator(IntObjectArray *o): obj(o), d_current(0) {}
    IntObject* begin(){}
    IntObject* end(){}
    IntObject* next(){}
    IntObject* prev() {}
};

Step 4

Use the above designed/implemented classes in the following code:

int main() {
    IntObjectArray *array = new IntObjectArray(20);
    IntObjectIterator it(array);

    while (it.current() != it.end()) {
        cout << "current value: " << it.current()->get() << endl;
            it.next();
    }
    delete array;
    return 0;
}

It should produce output as:

current value: 0
current value: 1
current value: 2
current value: 3
current value: 4
current value: 5
current value: 6
current value: 7
current value: 8
current value: 9
current value: 10
current value: 11
current value: 12
current value: 13
current value: 14
current value: 15
current value: 16
current value: 17
current value: 18
current value: 19
Sample Solutions
Subpages (1): Sample Solutions
Comments