C 迭代器
2016-03-30 23:58
441 查看
#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++实现JNI接口需要注意的事项
- 关于指针的一些事情
- 设计模式之行为型模式 - 调用行为的传递问题
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Ruby中的迭代器详解
- Ruby中Block和迭代器的使用讲解
- Lua中调用C++函数示例
- Lua中的迭代器浅析
- Lua中的迭代器和泛型for介绍
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C#特性-迭代器(上)及一些研究过程中的副产品
- C#迭代器模式(Iterator Pattern)实例教程
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析