Overview of Iterators in C++ STL

As we have discussed earlier, Iterators are used to point to the containers in STL, because of iterators it is possible for an algorithm to manipulate different types of data structures/Containers.

Algorithms in STL don’t work on containers, instead they work on iterators, they manipulate the data pointed by the iterators. Thus it doesn’'t matter what is the type of the container and because of this an algorithm will work for any type of element and we don't have to define same algorithm for different types of containers.

Overview of Iterators in STL

The above diagram shows to iterators i and j, pointing to the beginning and the end of a vector.


Defining an Iterator in STL

Syntax for defining an iterator is :

container_type <parameter_list>::iterator iterator_name;



Let's see an example for understanding iterators in a better way:


#include<iostream>
#include<vector>

using namespace std;

int main()
{
    vector<int>::iterator i;
    /* create an iterator named i to a vector of integers */
    
    vector<string>::iterator j;
    /* create an iterator named j to a vector of strings */
    
    list<int>::iterator k;
    /* create an iterator named k to a vector of integers */
    
    map<int, int>::iterator l;
    /* create an iterator named l to a map  of integers */
}

Iterators can be used to traverse the container, and we can de-reference the iterator to get the value of the element it is pointing to. Here is an example:


#include<iostream>
#include<vector>
int main()
{
    vector<int> v(10);
    /* creates an vector v : 0,0,0,0,0,0,0,0,0,0  */
    
    vector<int>::iterator i;
    
    for(i = v.begin(); i! = v.end(); i++)
    cout << *i <<"  ";
    /* in the above for loop iterator I iterates though the 
    vector v and *operator is used of printing the element 
    pointed by it.  */

return 0;
}