迭代器模式(Iterator)
来源:互联网 发布:win8如何设置网络连接 编辑:程序博客网 时间:2024/04/30 11:42
1.目的
当需要遍历(单种方式或多种方式)遍历一个组合对象时,使用遍历模式。该模式类似与将容器的接口进行封装,不对外直接暴露容器的接口的做法类似。
2.代码
#ifndef ITERATOR_H_#define ITERATOR_H_#include <list>#include <string>using namespace std;class PersonForIterator{public:PersonForIterator(){}string getName(){return name;}PersonForIterator(string arg){name = arg;}private:string name;};class Aggregate{public:virtual ~Aggregate(){}void insert(PersonForIterator& arg){lists.push_back(arg);}public:list<PersonForIterator> lists;};class Iterator{public:Iterator(Aggregate& agg):agg(agg){iter = agg.lists.begin();}PersonForIterator& first(){return *(agg.lists.begin());}PersonForIterator& next(){iter++;return *iter;}bool isDone(){return (iter == agg.lists.end());}private:Aggregate& agg;list<PersonForIterator>::iterator iter;};#endif /* ITERATOR_H_ */
#include "Iterator.h"#include <iostream>void iterator(){PersonForIterator p1("Tom");PersonForIterator p2("Allen");PersonForIterator p3("John");PersonForIterator p4("Jim");Aggregate agg;agg.insert(p1);agg.insert(p2);agg.insert(p3);agg.insert(p4);Iterator it(agg);PersonForIterator p = it.first();while(!it.isDone()){cout<<p.getName()<<endl;p = it.next();}}
输出:
Tom
Allen
John
Jim
0 0
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- Iterator(迭代器)模式
- 迭代器模式(Iterator)
- 迭代器(Iterator)模式
- 迭代器模式(Iterator)
- Iterator(迭代器模式)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 迭代器模式(Iterator)
- 为Date增加时间
- 启用Sqlite3 的Unlock Notification
- Playerprefs存储路径
- oracle 权限角色
- AFNetworking源码解析<三>
- 迭代器模式(Iterator)
- maven单元测试
- vc打开pdf入门(一)
- java多线程 之 ConcurrentHashMap
- HDU_ACM-2034 人见人爱A-B
- layoutSubviews总结
- 人脸识别初始
- varnish session - 不同的session,不同的缓存。 - varnish
- 大家好,我是廖记棒棒鸡,新生活,星播客