C++ Iterators


Iterators are used to access the individual elements in a container.

An iterator can be classified in the following ways:

  • Bidirectional Iterator
  • Forward Iterator
  • Input Iterator
  • Output Iterator
  • Random Access Iterator

Syntax:

 <ContainerType>:: iterator; 

#include <iostream> 
#include<iterator>  
#include<list>
using namespace std;  

int main()  
{  
   list<int> l={4,3,2,1};  
   list<int>::iterator it=l.begin();  
   l.insert(it,5);
   it=l.begin();  
   while(it!=l.end()) 
   { 
		cout << *it;  
		++it;
   }
   return 0;  
} 

Bidirectional Iterator

Bidirectional iterator is used to access the elements in both the directions.

Bidirectional iterator such as list, set, map, and etc.

Example:

 #include <iostream> 
#include<iterator>  
#include<list>
using namespace std;  

int main()  
{  
   list<int> l={4,3,2,1};  
   list<int>::iterator it=l.begin();
   list<int>::reverse_iterator rit=l.rbegin();   
   while(it!=l.end()) 
   { 
		cout << *it << " ";  
		++it;
   }
   cout << endl;
   while(rit!=l.rend()) 
   { 
		cout << *rit << " "; 
		rit++;
   }
   return 0;  
}

Forward Iterator

Forward iterator helps to read the contents from the beginning to the end of a container.


Input Iterator

Input Iterator is used to read the values from the container.

Example:

#include <iostream>  
#include<vector>  
#include<iterator>   
using namespace std;  

int main()  
{  
	vector<int> v{1,2,3,4,5};  
    vector<int>::iterator it,it1;  
    it=v.begin();  
    it1=v.begin()+2;  
    if(it==it1)
    { 
    	cout << "Both the iterators are equal" << endl;
	}  
    else{  
    	cout << "Both the iterators are not equal" << endl; 
    } 
    return 0;  
} 

Output Iterator

Output Iterator is used to modify the value in the container.

Example:

#include <iostream>  
#include<vector>  
#include<iterator>  
using namespace std;  

int main()  
{  
   list<int> l={4,3,2,1};  
   list<int>::iterator it=l.begin();  
   l.insert(it,5);
   it=l.begin();  
   while(it!=l.end()) 
   { 
		cout << *it;  
		++it;
   }
   return 0;  
} 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.