Summer 2003: Algorithm Library Design

Homework 3: Tuesday, 13.05.03

due Thursday , 22.05.03, 4pm (before class)
Submit homeworks to Roman Dementiev <dementiev@mpi-sb.mpg.de>. Source code only, no executables!

Exercise 3 (10 Pts)

(The source code for this exercise can be found at: oo_iterator.C.)

In object-oriented design we would start with a common base class for all iterators. Let us assume that the value type is fixed to char for now.

struct Iterator {
    virtual void advance()             = 0;
    virtual bool equal( Iterator* i)   = 0;
    virtual char get()                 = 0;
    virtual ~Iterator() {}
};
Write a concrete class for an iterator over C-arrays of characters using the following skeleton.
class Array_iterator : public Iterator {
    char* s;
public:
    ...
};
Write a generic function that finds a character in a range of two iterators. The range is defined as in the STL to be the half-open interval including begin but excludinglast. The function returns true if the character exists in the range [first,last).
bool contains( Iterator* first, Iterator* last, char c) {
    ...
}
Use a small test program to compile and check your solution.
#include <assert.h>

int main() {
    char* s = "Some useless text.";
    Array_iterator* begin = new  Array_iterator(s);
    Array_iterator* last  = new  Array_iterator(s+18);
    assert(   contains( begin, last, 'u'));
    // Note, iterator begin has been advanced to be equal to last here.
    delete begin;
    begin = new  Array_iterator(s);
    assert( ! contains( begin, last, 'q'));
    delete begin;
    delete last;
}

Keep a copy of this finished program.

Change the classes and the generic function to work with iterators of arbitrary value type. Make the value type a template parameter. Extend the test function to test now also with a small array of integer values.

Turn in both programs; the one with templates and the first one without templates.


Lutz Kettner (<surname>@mpi-inf.mpg.de). Last modified on Tuesday, 17-Jan-2006 17:53:42 MET.