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++23 implementation is based on chapter "Generalizing vector yet again".[5]
importstd;template<typenameT>usingInitializerList=std::initializer_list<T>;usingOutOfRangeException=std::out_of_range;template<typenameT>usingUniquePtr=std::unique_ptr<T>;classDoubleVector{private:UniquePtr<double[]>elements;size_tlistSize;public:usingIterator=double*;[[nodiscard]]Iteratorbegin()constnoexcept{returnelements;}[[nodiscard]]Iteratorend()constnoexcept{returnelements+listSize;}DoubleVector(InitializerList<double>list):elements{std::make_unique<double[]>(list.size())},listSize{list.size()}{double*p=elements;for(autoi=list.begin();i!=list.end();++i,++p){*p=*i;}// alternatively implemented with// std::ranges::copy(list, elements.get())}~DoubleVector()=default;[[nodiscard]]size_tsize()constnoexcept{returnlistSize;}[[nodiscard]]double&operator[](size_tn){if(n>=listSize){throwOutOfRangeException("DoubleVector::operator[] out of range!");}returnelements[n];}DoubleVector(constDoubleVector&)=delete;// disable copy constructionDoubleVector&operator=(constDoubleVector&)=delete;// disable copy assignment};intmain(intargc,char*argv[]){DoubleVectorv={1.1*1.1,2.2*2.2};for(constdouble&x:v){std::println("{}",x);}for(size_ti=v.begin();i!=v.end();++i){std::println("{}",*i);}for(size_ti=0;i<=v.size();++i){std::println("{}",v[i]);}}
The program output is
1.214.841.214.841.214.84terminatecalledafterthrowinganinstanceof'OutOfRangeException'what():DoubleVector::operator[]outofrange!