// ********** IteratorDemo.cpp ********** #include #include using namespace std; #define null 0 class Integer { private: int i; public: Integer(int i) { this->i = i; } int intValue() { return i; } }; class IteratorIF { public: virtual Integer* next() = 0; virtual bool hasNext() = 0; }; const int MAX_SIZE = 500000; class IteratorCollection { private: Integer* array[MAX_SIZE]; int total; public: friend class FriendlyIterator; IteratorCollection() { total = 0; } void addItem(Integer* item) { if (total < MAX_SIZE) array[total++] = item; } FriendlyIterator* createIterator() const; }; class FriendlyIterator : public IteratorIF { private: const IteratorCollection* collection; int index; public: FriendlyIterator(const IteratorCollection* coll) { collection = coll; index = -1; } Integer* next() { return collection->array[index]; } bool hasNext() { if (index < collection->total-1) { index ++; return true; } else return false; } }; FriendlyIterator* IteratorCollection::createIterator() const { return new FriendlyIterator( this ); } int main () { hrtime_t t1 = gethrtime(); for (int j=0; j<5; j++) { IteratorCollection* collection = new IteratorCollection(); for (int i=0; iaddItem(new Integer(i)); IteratorIF* iterator = collection->createIterator(); while (iterator->hasNext()) { Integer* item = iterator->next(); //cout << item->intValue() << endl; } } hrtime_t t2 = gethrtime(); cout << (t2-t1)/1000000 << " "; return 1; }