More C++ Idioms/Iterator Pair

= Iterator Pair =

Intent
Specify a range of data values without worrying about the underlying data structure used by the data values.

Also Known As
Sometimes this is referred to as an Iterator Range.

Motivation
It is well understood that it is useful to create a vector from another vector using a copy constructor. Similarly, it is useful to create a vector from a vector using Coercion by Member Template idiom applied on a member template constructor. A code example is given below.

The vector interface is still not flexible enough for some needs. For example, A vector can't create itself from a list or a set or a POD array. Iterator-pair is an idiom that addresses this challenge. It is based on the Iterator design pattern (obviously!) Iterator pattern intent: Provide an object which traverses some aggregate structure, abstracting away assumptions about the implementation of that structure.

Solution and Sample Code
A pair of iterators is used to designate a beginning and an end of a range of values. By virtue of the iterator design pattern whoever (in our example vector) uses iterator pair idiom can access the range without worrying about the implementation of the aggregate data structure. The only requirement is that the iterators should expose a fixed, minimal interface such as a pre-increment operator.

Iterator-pair idiom is often combined with member templates because the exact type of the iterators is not known apriori. It could be set::iterator or list::iterator or a POD array. Irrespective of the type, any generic algorithm written in terms of the iterator pairs works. It is often useful to indicate the concept that iterator types are supposed to model. In the example above, the iterators are required to model at least the InputIterator concept. More information about iterator categories (tags) and their uses are described in Tag Dispatching idiom.

Sometime iterator pair idiom is unavoidable. For example, to construct a std::string from a buffer of characters with embedded null characters iterator-pair idiom is unavoidable.

Known Uses
All standard containers

Related Idioms

 * Coercion by Member Template
 * Tag Dispatching