Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are all pointers considered iterators?

Tags:

c++

This was a question on my exam and the answer is that all pointers are iterators but not all iterators are pointers. Why is this the case?

In a statement such as:

int *p = new int(4);

How can p be considered an iterator at all?

like image 512
StarckOverflar Avatar asked Dec 23 '22 22:12

StarckOverflar


1 Answers

"Iterator" is some abstract concept, describing a certain set of operations a type must support with some specific semantics.

Pointers are iterators because they fulfill the concept iterator (and, even stronger, random access iterator), e.g. the operator++ to move to the next element and operator * to access the underlying element.

In your particular example, you get a standard iterator range with

[p, p+1)

which can be used for example in the standard algorithms, like any iterator pair. (It may not be particularly useful, but it is still valid.) The above holds true for all "valid" pointers, that is pointers that point to some object.

The converse implication however is false: For example, consider the std::list<T>::iterator. That is still an iterator, but it cannot be a pointer because it does not have an operator[].

like image 131
Baum mit Augen Avatar answered Jan 07 '23 00:01

Baum mit Augen