标签:c++迭代器
#include <iostream> #include <cstdlib> using namespace std; template<class T,int ssize=100> class MyList { T data[ssize]; int length; public: MyList (){length=0;} void push_back(const T&i) { if(length>=ssize-1)exit(1); data[length++]=i; } bool empty() { return(length==0); } class iterator; friend class iterator; class iterator { MyList&lst; int index; public: iterator(MyList &l):lst(l) { index=0; } iterator(MyList &l,bool):lst(l) { index=l.length; } T operator*() const { if(index>=0) return lst.data[index]; else exit(1); } T operator++() { if(index>lst.length) exit(2); return lst.data[++index]; } T operator++(int) { if(index>lst.length) exit(3); return lst.data[index++]; } T operator--() { if(index<=0) exit(4); return lst.data[--index]; } T operator--(int) { if(index<=0) exit(5); return lst.data[index--]; } bool operator!=(const iterator &rv)const { return index!=rv.index; } bool operator==(const iterator &rv)const { return index==rv.index; } bool operator<=(const iterator &rv)const { return index<=rv.index; } bool operator<(const iterator &rv)const { return index<rv.index; } bool operator>=(const iterator &rv)const { return index>=rv.index; } bool operator>(const iterator &rv)const { return index>rv.index; } }; iterator begin() { return iterator(*this); } iterator end() { return iterator(*this,true); } }; int main() { MyList<int> lst; lst.push_back(1); lst.push_back(2); lst.push_back(3); lst.push_back(4); MyList<int>::iterator iter=lst.begin(); cout<<"从表头到表尾:"; for (; iter!=lst.end();iter++) cout<<*iter<<" "; cout<<endl; MyList<int>::iterator iterl=lst.end(); cout<<"从表尾到表头:"; iterl--; for (; iterl>=lst.begin();iterl--) cout<<*iterl<<" "; cout<<*iterl<<endl; }
标签:c++迭代器
原文地址:http://sts609.blog.51cto.com/11227442/1758665