Create a Random-Access Iterator
Learn to create a random-access iterator.
We'll cover the following...
This recipe is an example of a full-featured contiguous iterator, also called a random-access iterator. This is the most complete type of iterator for a container. A random-access iterator includes all the features of all the other types of container iterators, along with its random-access capabilities.
How to do it
We need a container for our iterator. We’ll use a simple array for this, and we’ll call it Container
. The iterator
class is nested within the Container
class.
All of this is designed to be consistent with the STL container interfaces.
Container
is defined as atemplate
class. Itsprivate
section has only two elements:
template<typename T>class Container {std::unique_ptr<T[]> c_{};size_t n_elements_{};
We use a unique_pointer
for the data. We let the smart pointer manage its own memory. This mitigates the need for a ~Container()
destructor. The n_elements_
variable keeps the size of our container.
In the public section, we have our constructors:
Container(initializer_list<T> l) : n_elements_{l.size()} {c_ = std::make_unique<T[]>(n_elements_);size_t index{0};for(T e : l) {c_[index++] = e;}}
The first constructor uses an initializer_list
to pass elements for the container. We call make_unique
to allocate space and populate the container with a range-based for
...