Inobject-oriented programming, theiterator pattern is adesign pattern in which aniterator is used to traverse acontainer and access the container's elements. The iterator pattern decouplesalgorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.
For example, the hypothetical algorithmSearchForElement can be implemented generally using a specified type of iterator rather than implementing it as a container-specific algorithm. This allowsSearchForElement to be used on any container that supports the required type of iterator.
The Iterator[1]design pattern is one of the 23 well-known"Gang of Four" design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
Defining access and traversal operations in the aggregate interface is inflexible because it commits the aggregate to particular access and traversal operations and makes it impossible to add new operationslater without having to change the aggregate interface.
Different iterators can be used to access and traverse an aggregate in different ways.
New access and traversal operations can be defined independently by defining new iterators.
See also the UML class and sequence diagram below.
The essence of the Iterator Pattern is to "Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.".[3]
In the aboveUMLclass diagram, theClient
class refers (1) to theAggregate
interface for creating anIterator
object (createIterator()
) and (2) to theIterator
interface for traversing anAggregate
object (next(),hasNext()
).TheIterator1
class implements theIterator
interface by accessing theAggregate1
class.
TheUMLsequence diagramshows the run-time interactions: TheClient
object callscreateIterator()
on anAggregate1
object, which creates anIterator1
object and returns itto theClient
.TheClient
uses thenIterator1
to traverse the elements of theAggregate1
object.
Some languages standardize syntax. C++ and Python are notable examples.
C++ implements iterators with the semantics ofpointers in that language. In C++, a class can overload all of the pointer operations, so an iterator can be implemented that acts more or less like a pointer, complete with dereference, increment, and decrement. This has the advantage that C++ algorithms such asstd::sort
can immediately be applied to plain old memory buffers, and that there is no new syntax to learn. However, it requires an "end" iterator to test for equality, rather than allowing an iterator to know that it has reached the end. In C++ language, we say that an iterator models the iteratorconcept.
This C++11 implementation is based on chapter "Generalizing vector yet again".[5]
#include<iostream>#include<stdexcept>#include<initializer_list>classVector{public:usingiterator=double*;iteratorbegin(){returnelem;}iteratorend(){returnelem+sz;}Vector(std::initializer_list<double>lst):elem(nullptr),sz(0){sz=lst.size();elem=newdouble[sz];double*p=elem;for(autoi=lst.begin();i!=lst.end();++i,++p){*p=*i;}}~Vector(){delete[]elem;}intsize()const{returnsz;}double&operator[](intn){if(n<0||n>=sz)throwstd::out_of_range("Vector::operator[]");returnelem[n];}Vector(constVector&)=delete;// rule of threeVector&operator=(constVector&)=delete;private:double*elem;intsz;};intmain(){Vectorv={1.1*1.1,2.2*2.2};for(constauto&x:v){std::cout<<x<<'\n';}for(autoi=v.begin();i!=v.end();++i){std::cout<<*i<<'\n';}for(autoi=0;i<=v.size();++i){std::cout<<v[i]<<'\n';}}
The program output is
1.214.841.214.841.214.84terminatecalledafterthrowinganinstanceof'std::out_of_range'what():Vector::operator[]