一. 举例说明

我们知道,在 STL 里提供 Iterator 来遍历 Vector 或者 List 数据结构。

Iterator 模式也正是用来解决对一个聚合对象的遍历问题,将对聚合的遍历封装到一个类中进行,这样就避免暴露这个聚合对象的内部表示的可能。

例如在 STL 里有如相下结构:

设计模式C++描述----20.迭代器(Iterator)模式

二. 迭代器模式

定义:提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示

设计模式C++描述----20.迭代器(Iterator)模式

比较经典的例子是 STL 里的 for_each 操作

    1. // function called for each element    
    2. void print (int elem)    
    3. {    
    4.     cout << elem << ' ';    
    5. }    
    6.     
    7. int main()    
    8. {    
    9.         vector<int> coll;    
    10.     
    11.         INSERT_ELEMENTS(coll,1,9);    
    12.     
    13.         // for_each 对每个 elem 将调用 print(elem)    
    14.         for_each (coll.begin(), coll.end(),  // range    
    15.                   print);                    // operation    
    16.         cout << endl;    
    17. }   

相关文章:

  • 2022-12-23
  • 2021-12-11
  • 2022-12-23
  • 2021-07-15
  • 2021-11-21
猜你喜欢
  • 2022-12-23
  • 2021-07-04
  • 2021-05-22
  • 2021-09-20
  • 2021-10-03
  • 2021-12-20
  • 2021-06-21
相关资源
相似解决方案