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?
"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[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With