首页 > 其他 > 详细

初学设计模式之迭代器模式

时间:2019-11-10 11:39:23      阅读:84      评论:0      收藏:0      [点我收藏+]

概念与定义

迭代器模式提供一种方法访问一个容器对象中各个元素,而又不需要暴露该对象的内部细节

 

迭代器模式的应用

迭代器模式是一种退化的设计模式,因为它的使用过于普遍,因此被嵌入到具体语言中了,C++使用迭代器读取其中元素的例子

 1 //迭代器
 2 
 3 #include<iostream>
 4 #include<vector>
 5 #include<string>
 6 #include<list>
 7 
 8 using namespace std;
 9 
10 int main()
11 {
12 vector<string>m_vector;
13 list<string>m_list;
14 string m_str[] ={"A","B","C","D","E"};
15 
16 //向容器里面添加元素
17 for(int i=0;i<sizeof(m_str)/sizeof(m_str[0]);i++)
18 {
19     m_vector.push_back(m_str[i]);
20     m_list.push_back(m_str[i]);
21 };
22 
23 //利用迭代器读取容器里面的元素
24 for(vector<string>::iterator iter=m_vector.begin();iter!=m_vector.end();iter++)
25 {
26     cout<<*iter<<endl;
27 }
28 
29 for(list<string>::iterator iter=m_list.begin();iter!=m_list.end();iter++)
30 {
31     cout<<*iter<<endl;
32 }
33 
34 getchar();
35 return 0;
36 };

 

初学设计模式之迭代器模式

原文:https://www.cnblogs.com/wuhongjian/p/11829041.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!