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.
Constant Iterators:
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.
Regular Iterators:
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:
C++
// C++ program to demonstrate a regular // and const_iterator #include <iostream> #include <iterator> #include <vector> using namespace std; // Function that demonstrate regular // iterators void regularIterator(vector< int >& v) { // Declare a regular iterator // to a vector vector< int >::iterator i; // Printing the elements of the // vector v using regular iterator for (i = v.begin(); i < v.end(); i++) { // Update elements of vector *i += 1; cout << *i << " " ; } } // Function that demonstrate const // iterators void constIterator(vector< int >& v1) { // Declare a const_itearor // to a vector vector< int >::const_iterator ci; // Printing the elements of the // vector v1 using regular iterator for (ci = v1.begin(); ci < v1.end(); ci++) { // Below line will throw an error // as we are trying to modify the // element to which const_iterator // is pointing //*ci += 1; cout << *ci << " " ; } } // Driver Code int main() { // Declaring vectors vector< int > v = { 7, 2, 4 }; vector< int > v1 = { 5, 7, 0 }; // Demonstrate Regular iterator regularIterator(v); cout << endl; // Demonstrate Const iterator constIterator(v1); return 0; } |
8 3 5 5 7 0