Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are iterators and pointers related?

Code with iterators looks pretty much like code with pointers. Iterators are of some obscure type (like std::vector<int>::iterator for example).

What I don't get is how iterators and pointer are related to each other - is an iterator a wrapper around a pointer with overloaded operations to advance to adjacent elements or is it something else?

like image 295
sharptooth Avatar asked Apr 28 '10 09:04

sharptooth


People also ask

Are iterators and pointers the same?

A pointer hold an address in memory. An iterator may hold a pointer, but it may be something much more complex. For example, an iterator can iterate over data that's on file system, spread across many machines, or generated locally in a programmatic fashion.

Why use iterators instead of pointers?

After all, iterators are invalidated at mostly the same times and the same ways as pointers, and one reason that iterators exist is to provide a way to "point" at a contained object. So, if you have a choice, prefer to use iterators into containers.

Which statement about the difference between pointer and iterator is true?

Which of the following is a true statement about the difference between pointers and iterators? While pointers are variable that hold memory address, iterators are generic functions used to traverse containers. These function allows the programmer to implement read and write code as the container is traversed.

Are iterators faster than pointers?

Iterators is a generic concept. They work on all sorts of containers and have similar interface. Accessing the array element directly like arr_int[i] is definitely faster because it directly translates to pointer arithmetic.


1 Answers

Iterators are a generalization of pointers.

An iterator (depending on the variants) have to implement * and ++

So a pointer IS an iterator. But not necessarily the other way round.

If you want to iterate over a complex structure (a tree, a graph...), the iterator will be much more than a pointer, and doesn't make any reference to some actual place in the ram.

like image 168
Tristram Gräbener Avatar answered Sep 25 '22 22:09

Tristram Gräbener