I can’t understand the main purpose of iterators. Googling, I did not understand everything equal.
- What is an iterator?
- Why do you need it?
- Benefits on a pointer
- How to describe it programmatically in code? (that is, make your iterator
similar to library ones).
Answer 1, authority 100%
Look. You have a container. It doesn’t matter which one:
set . It contains a collection of elements. And you don’t want to refer to the entire container, but to some place in that set of elements. So that from this place you can go forward / backward, and do something in this place: change an element, insert an element, delete an element.
How to do it? For an array, you use an index in such cases. The
set is internally a red-black tree, so you need a link to a node in that tree.
unordered_map uses a hash table, so you need a pair of hash index and a pointer to the element inside the bucket.
To avoid having to write algorithms specific to each container, iterators were invented.
An iterator is a data structure that “points” to a certain element of the container, and (for some containers) is able to move 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, for example, you want to implement
RandomAccessIterator , you have to define a copy constructor, assignment operator, destructor, operations
! = ,
- & gt; , no-argument constructor,
+ = ,
+ (2 pcs. ),
- = ,
- (2 pcs.),
& lt; ,
& gt; ,
& lt ; = ,
& gt; = . (Other types of iterators are simpler.)
In addition, you will need to specify
std :: iterator_traits & lt; It & gt; , where
It is the type of your iterator.
Here’s a template for your own container on SO. A lot, right?
Answer 2, authority 38%
An iterator is an object that allows you to move (iterate) over the elements of some sequence.
The use of such objects is classified as the Iterator programming pattern.
A sequence can be either a ready-made set of objects in memory, or it can consist of objects that are created “on the fly” when the iterator is moved (for example, read from a file).
Unlike various sequences of elements (arrays, lists, files), iterators have the same interface: get the current element, move to the next. This allows more general algorithms to be written that work with any iterators that support this minimal set of functions.
The C++ Standard Library iterators repeat the pointer interface. This allows pointers to array elements to be used as iterators. Moreover, most algorithms use only a certain minimal set of operations, for example, only moving forward. This set of operations is called category , a list of all categories of iterators is listed here .
Options for writing your own iterator are in the answers to this question .