У вас вопросы?
У нас ответы:) SamZan.net

Declrtion of the clss to be defined lter templte [clss Item] clss CItertor; -- n bstrct continer something tht contins elements -- but how it stores them in not defined- the conti

Работа добавлена на сайт samzan.net: 2015-07-05

Поможем написать учебную работу

Если у вас возникли сложности с курсовой, контрольной, дипломной, рефератом, отчетом по практике, научно-исследовательской и любой другой работой - мы готовы помочь.

Предоплата всего

от 25%

Подписываем

договор

Выберите тип работы:

Скидка 25% при заказе до 10.3.2025

PAGE  1

Iterator pattern

#include <iostream>

#include <stdio.h>

using namespace std;

// just a pre-declaration of the class, to be defined later

template <class Item> class CIterator;

// an abstract container - something that contains elements,

// but how it stores them in not defined: the container does not

// expose its structure. the only way to access elements in the

// container is to ask it for an iterator

template <class Item>

class CContainer

{

public:

 // the abstract container can only create an iterator,

 // which can be used to access its elements

 virtual CIterator<Item> *createIterator() = NULL;

};

// an abstract iterator - something, that allows to retrieve

// objects from the container sequentially

template <class Item>

class CIterator

{

public:

 // move to the first element

 virtual void first() = NULL;

 // get current element

 virtual Item getCurrentItem() = NULL;

 // set current element

 virtual void setCurrentItem(Item item) = NULL;

 // move to the next element

 virtual void next() = NULL;

 // have we moved out of the elements in the list?

 virtual bool isEOL() = NULL;

};

// just a pre-declaration of the class, to be defined later

template <class Item> class CArrayIterator;;

// a real concrete container, an array in this case,

// which allows to get the number of elements and to

// access (get or set) random element:

// note, it is NOT the the same way as to access with CIterator

template <class Item>

class CArray : public CContainer<Item>

{

private:

Item *_values;

 int _size;

public:

CArray(int size)

{

 _size = size;

 _values = new Item[_size];

}

 virtual int getCount()

{

 return _size;

}

 virtual Item getValue(int index)

{

 return _values[index];

}

 virtual void setValue(int index, Item item)

{

 _values[index] = item;

}

 // of course, we may work with CArray directly through getValue and setValue

 // if we know that it is CArray, and not merely CContainer, but another way

 // to access data is to retrieve an iterator first, and access through it

 virtual CIterator<Item> *createIterator()

{

 // a CArray known which iterator can access its data and creates it here

 return new CArrayIterator<Item>(this);

}

};

// a concrete array iterator - something, that can retrieve elements from the

// concrete CArray sequentially, the way it is defined by CIterator

template <class Item>

class CArrayIterator : public CIterator<Item>

{

private:

 // an array iterator holds a link to CArray

CArray<Item> *_arr;

 // and an internal counter of the current element

 int _current_index;

public:

CArrayIterator(CArray<Item> *arr)

{

 _arr = arr;

 _current_index = 0;

}

 virtual void first()

{

 _current_index = 0;

}

 virtual Item getCurrentItem()

{

 if (!isEOL())

  return _arr->getValue(_current_index);

 else

  return 0;

}

 virtual void setCurrentItem(Item item)

{

 if (!isEOL())

  _arr->setValue(_current_index, item);

}

 virtual void next()

{

 if (!isEOL())

  _current_index++;

}

 virtual bool isEOL()

{

 return _current_index == _arr->getCount();

}

};

void main()

{

 // lets create an array of 'ints'

CArray<int> arr(10);

 

 // knowing that we have created CArray, we can manually

 // create an appropriate iterator, that is CArrayIterator:

 

 // CArrayIterator<int> *i = new CArrayIterator<int>(&arr);

 

 // but it's not very good, - we'd better ask an array itself

 // to create an appropriate iterator for us - thus we do not

 // have to know to what real container class 'arr' belongs to

CIterator<int> *i = arr.createIterator();

 

 // now we may use standard methods of CIterator to access

 // elements of our container; here we know nothing about

 // exact class of 'arr' and 'i' - for us here it's just

 // an abstract container and abstract class

 for(i->first(); !i->isEOL(); i->next())

{

 i->setCurrentItem(rand());

}

 

 // again, iterate and access

 for(i->first(); !i->isEOL(); i->next())

{

 printf("%d ", i->getCurrentItem());

}

printf("\n");

 // delete iterator

 delete i;

 

 char c; cin >> c;

}




1. Как передать нужную информацию нужному адресату в тайне от других Имеется три возможности решени
2. статтях фінансової звітності
3. РОССИЙСКАЯ АКАДЕМИЯ ПРАВОСУДИЯ Центральный филиал Кафедра
4. Мова та історія (розвиток мови
5. РЕФЕРАТ дисертації на здобуття наукового ступеня доктора педагогічних наук
6. тематическим употреблением спиртных напитков характеризующееся патологическим влечением к ним развитием
7. Виробництво виробів і конструкцій із деревини і пластмас
8. Статья- Химико-аналитические методы исследования состава воды
9. Влияние теоретических представлений о развитии общества на программы левых партий
10. 1Фази інноваційного процесу Інноваційним процесом як правило називають підготовку та поступове зді