As it was said: iterators are a generalization of pointers. Every pointer is an iterator but not every iterator is a pointer (although most of non-pointer iterators contain pointers within).
Iterator is kind of interface (or concept). We could define the minimum iterator interface as follows:
template <typename T>
class iterator
{
// Advance to the next element of the collection.
virtual void operator++() = 0;
// Get access to the element associated with the iterator.
virtual const T &operator*() = 0;
};
But there is no real abstract base class for iterators. All functions that take iterators as parameters are template functions, and types for iterator parameters are defined using templates. This is called static polymorphism. We can use std::vector
constructor as an example:
template< class InputIt >
vector::vector( InputIt first, InputIt last );
Since InputIt
is a type defined using template and since all pointers support operator++()
and operator*()
, all pointers can be used as iterators. For example:
int arr[3] = {1, 2, 3};
int *begin = &arr[0];
int *end = &arr[3];
// Initialize vector from a pair of iterators.
std::vector<int> v(begin, end); // The vector `v` will copy to itself
// all elements of `arr` in the range from
// arr[0] (including) to arr[3] (excluding).
or
std::string str = "hello";
std::string *begin = &str;
std::string *end = begin + 1;
// Initialize vector from a pair of iterators.
std::vector<std::string> v(begin, end); // The vector `v` will contain
// a single element which is
// string "hello".
Since iterator is just an abstract interface, pointers are not the only example of iterators. Any class that overrides operator++()
and operator*()
can be used as an iterator. And usually containers use custom classes as iterators instead of pointers. But some functions still use pointers as iterators. An example is std::begin
and std::end
functions for static arrays:
template< class T, std::size_t N >
T* begin( T (&array)[N] );
template< class T, std::size_t N >
T* end( T (&array)[N] );
There are different types of iterators. The most advanced type of iterator is Random Access Iterator. Besides operator++()
and operator*()
it supports many other operations like advancing backward (operator--()
) or advancing many elements forward at single step (operator+=(size_t n)
). Pointers are Random Access Iterators.
This is how pointers and iterators are related.
Resume. Iterators are class of objects that allows to iterate through some collection of elements. Pointers are just an example of iterators but there are others.