What is Iterator?

Studying STL in C++, I almost always come across the term iterator, example:

std::vector<int>::iterator it;

What is the function of a iterator?

Author: Maniero, 2016-11-08

2 answers

Is the mechanism used to" walk", element by Element, through a collection of data. It is an abstract and generic way of treating the advancement between the elements of this collection. This advance can occur in several ways, including the opposite.

The exact operation depends on each type of data, the important thing is that if a type has an iterator in accordance with the language any operation that iteration can be done with that object. It does not matter to him the complexity of the operation, nor how it should be done. It is an implementation-independent way of accessing collection data.

It has the methods begin() e end() to indicate where the iteration begins and ends.

Example:

#include <iostream>
#include <vector>
using namespace std;

int main () {
    vector<int> vetor;
    for (int i = 0; i < 10; i++) vetor.push_back(i);
    for (auto it = vetor.begin(); it != vetor.end(); it++) cout << ' ' << *it;
}

See working on ideone. E no repl.it. also I put on GitHub for future reference .

If you are creating a type that is a collection of data, a lot you should probably implement an iterator for this type. There are a number of rules to follow.

Documentation of the C++iteration library .

 14
Author: Maniero, 2020-11-12 19:14:04

The iterator is also known as a cursor that provides a sequential way to access the elements of a collection without exposing its internal representation.

If you know that your List is an ArrayList, then there is no problem using the index instead of using an Iterator. For all other types (LinkedList, Set, Map etc.) you have to use the Iterator.

And anyway you continue to use for:

 for valor in sequencia:
     print(valor)

It can be used when:

  • we want isolate the use of a data structure from its internal representation so that you can change the structure without affecting who uses it
  • for certain structures, there may be different ways of walking ("traversal") and we want to encapsulate the exact way of walking
  • the mere substitution of an iterator allows you to walk in a collection of various forms

There are also two types of iterators: interno and externo.

with built-in iterator, the client passes an operation to be performed by the iterator and it applies it to each element.

with external iterator (more flexible), the client uses the Iterator interface to walk but itself (the client) processes the elements of the collection

In this case an internal iterator is only used when an external iterator is difficult to implement.

Sources:

Https://pt.wikipedia.org/wiki/Iterador
http://www.guj.com.br/t/qual-e-a-vantagem-do-iterator/35565

 5
Author: Mauro Alexandre, 2016-11-08 18:55:47