64,677
社区成员
发帖
与我相关
我的任务
分享
//template <class T> class SNode;
template <class T>
class SList{
public:
class iterator;//这个iterator是否可以通过继承某个迭代器类而得来呢?像ios继承ios_base一样。
};
template<class T , class Ref , class Ptr >
class SList_Iterator
{
typedef SList_Iterator<T,T&,T*> iterator;
typedef SList_Iterator<T,const T&,const T*> const_iterator;
typedef SList_Iterator<T,Ref,Ptr> self;
typedef bidirectional_iterator_tag iterator_category; //这是SList_Iterator的成员变量吗?
typedef T value_type;
typedef Ptr pointer;
typedef Ref reference;
typedef SListNode<T> list_node;
//其它变量及操作定义
};
owenliang@linux-7lsl:~/csdn/src> cat main.cpp
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
template <class T>
class VecIterator
{
public:
typedef random_access_iterator_tag iterator_category;
typedef typename vector<T>::value_type value_type;
typedef typename vector<T>::difference_type difference_type;
typedef typename vector<T>::pointer pointer;
typedef typename vector<T>::reference reference;
VecIterator(vector<T> *v,int idx):vec(v),index(idx)
{
}
//VecInterator(const Vec....&) 不写了
VecIterator& operator = (const VecIterator &iter)
{
index=iter.index;
vec=iter.vec;
}
VecIterator& operator ++ ()
{
++index;
return *this;
}
T& operator * ()
{
return (*vec)[index];
}
private:
int index;
vector<T> *vec;
};
//配套萃取器,用于STL algorithm函数库,使用默认的即可
int main()
{
const int arr[]={1,2,3,4,5,6};
vector<int> vec(arr,arr+sizeof(arr)/sizeof(arr[0]));
VecIterator<int> iter(&vec,0);
//没法修改vector源码,所以没法用end(),暂且算了
for(int i=0;i<sizeof(arr)/sizeof(arr[0]);++i,++iter)
{
cout<<*iter<<endl;
}
return 0;
}
owenliang@linux-7lsl:~/csdn/src>
template <class T>
class SList<T>::iterator{
public:
iterator();
bool operator ==(const iterator & rhs ) const;
bool operator !=(const iterator & rhs ) const;
T& operator *();//overload pointer operator
iterator &operator++();
iterator &operator++(int);
iterator &operator--();
iterator &operator--(int);
private:
SNode<T> *pnode;// point to the current node
iterator(SNode<T> *p);//assign p to pnode
};