iterator.h

来自「设计模式模板源码」· C头文件 代码 · 共 88 行

H
88
字号
/////////////////////////////////////////////////////////////////////////////
// Iterator.h : iterator 
//

#ifndef _XP_ITERATOR_H__
#define _XP_ITERATOR_H__


template <typename _Elem>
class IteratorBase 
{
public:

	typedef _Elem Element;
	virtual ~IteratorBase() {}

public:
	virtual Element Next() = 0;
	virtual Element Prev() = 0;
	virtual Element Current() = 0;
	virtual XPBool Finished() = 0;
	virtual void Start() = 0;
};



template <typename _Aggr, typename _Iter = _Aggr::iterator, typename _Elem = _Aggr::value_type>
class Iterator
	: public IteratorBase<_Elem>
{
public:
	explicit Iterator(_Aggr& acollection): _coll(acollection) {Start();}

public:

	// Polymorphic iteration methods
	virtual Element Next();
	virtual Element Prev();
	virtual Element Current();
	virtual XPBool Finished();
	virtual void Start();

private:
	_Aggr& _coll;
	_Iter _it;
};


template <typename _Aggr, typename _Iter, typename _Elem>
Iterator<_Aggr, _Iter, _Elem>::Element 
Iterator<_Aggr, _Iter, _Elem>::Next()
{
	++_it;
	return Current();
}

template <typename _Aggr, typename _Iter, typename _Elem>
Iterator<_Aggr, _Iter, _Elem>::Element 
Iterator<_Aggr, _Iter, _Elem>::Prev()
{
	--_it;
	return Current();
}

template <typename _Aggr, typename _Iter, typename _Elem>
Iterator<_Aggr, _Iter, _Elem>::Element 
Iterator<_Aggr, _Iter, _Elem>::Current()
{
	return *_it;
}

template <typename _Aggr, typename _Iter, typename _Elem>
XPBool 
Iterator<_Aggr, _Iter, _Elem>::Finished()
{
	return _it == _coll.end();
}

template <typename _Aggr, typename _Iter, typename _Elem>
void 
Iterator<_Aggr, _Iter, _Elem>::Start()
{
	_it = _coll.begin();
}


#endif // #ifndef __ITERATOR_H__

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?