See it. Let you have a container. No matter what: map
, vector
, set
. It contains a set of items. And you want to refer not to the entire container, but to some place in this set of elements. So that from this place it was possible to go forward / back, and to do something in this place: change the element, insert the element, delete the element.
How to do it? For an array, you use an index in such cases. set
inside is a red-black tree, so you need a reference to the node of this tree. unordered_map
uses a hash table, so you need a pair of a hash index and a pointer to an element inside a bucket.
That it was not necessary to write the algorithms specific to each container, and iterators were thought up.
An iterator is a data structure that “points” to some element of the container, and (for some containers) can navigate to the previous / next element.
If you want to implement an iterator, remember that there are different types of iterators, depending on the operations they provide. Here is a list of possible types.
If you, for example, want to implement a RandomAccessIterator
, you have to define a copy constructor, an assignment operator, a destructor, ==
RandomAccessIterator
!=
, *
, ->
operations, a constructor without arguments, ++
, --
, +=
, +
(2 pcs. ), -=
, -
(2 pcs.), <
, >
, <=
, >=
. (Other types of iterators are simpler.)
In addition, you will have to specify std::iterator_traits<It>
, where It
is the type of your iterator.
Here's a blank for your own container on SO. A lot, right?