What is Iterator?

11

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

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

What is the function of a iterator ?

    
asked by anonymous 08.11.2016 / 19:44

2 answers

12

It is the mechanism used to "walk", element by element, by a collection of data. It is an abstract and generic way of treating the advance between the elements of this collection. This breakthrough can take many forms, including the other way around.

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 independent way of implementing access to collection data.

It has the methods begin() and 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 (vector<int>::iterator it = vetor.begin(); it != vetor.end(); it++) {
        cout << ' ' << *it;
    }
}

See running on ideone and on CodingGround .

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

C ++ Iteration Library Documentation .

    
08.11.2016 / 19:58
4

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

If you know that your List is an ArrayList, then there is no problem in 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 the for:

 for valor in sequencia:
     print(valor)

It can be used when:

  • We want to isolate the use of a data structure from its internal representation so that we can change the structure without affecting who uses it
  • For certain structures, there may be different forms of "traversal" and we want to encapsulate the exact form of walking
  • Simply replacing an iterator allows you to walk in a collection of many shapes

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

With an internal iterator, the client passes an operation to be performed by the iterator and iterates it to each element.

With an external (more flexible) iterator, the client uses the iterator interface to walk but it (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:

link
link

    
08.11.2016 / 19:49