Const vs Regular iterators in C++ with examples
Prerequisite: Iterators in STL
Iterators are objects similar to pointers which are used to iterate over a sequence and manipulate the container elements. The advantage of using an iterator is that it reduces the lines of code to a single statement as they allow us to manipulate the built-in arrays in the STL using pointers as iterators. An iterator can either be a constant or a non-constant/regular iterator.
A const iterator points to an element of constant type which means the element which is being pointed to by a const_iterator can’t be modified. Though we can still update the iterator (i.e., the iterator can be incremented or decremented but the element it points to can not be changed). It can be used for access only, and can’t be used for modification. If we try to modify the value of the element using const iterator then it generates an error.
A regular or non const_iterator points to an element inside the container and can be used to modify the element to which it is pointing. Regular Iterators play a critical role in connecting algorithm with containers along with the manipulation of data stored inside the containers. The most obvious form of a regular iterator is a pointer.
A pointer can point to elements in an array and can iterate through them using the increment operator(++). Each container type has a specific regular iterator type designed to iterate through its elements.
Below is a C++ program to demonstrate the difference in the working of the two iterators:
8 3 5 5 7 0