Iterators are opaque objects that allow to browse through a certain collection of objects in a unified way (always the same way), even though the collections may have a very different internal structure. For example: a std::map
is usually implemented as a red-black tree, std::vector
is an array occupying a block of memory. Going through all of the elements in vector is very different than going through all of the elements in a tree. Iterators abstract it for you - you always do it the same way (using ++ and -- operators and iterators):
auto iter = .begin();
auto end = .end();
//go through all elements of the container:
while(iter != end)
{
//do something
++iter;
}
Certain C++ compiler optimizations boil down to use pointers (e.g. std::string iterators usually would be compiled to just pointers to characters with optimizations turn on).