C++ program to find the type of the given iterator

C++Server Side ProgrammingProgramming

An iterator is an object just like a pointer that is used to iterate over elements of a container. The main advantage of using an iterator is to create a common interface and make the algorithm immune from the type of container used to implement it.

In C++ standard library there are Types of iterators −

  • Forward iterator
  • Bidirectional iterator
  • Input iterator
  • Output iterator
  • Random Access iterator

The program is to check which of the above iterators are used by the data structure.

There are a few factors that can be useful for determining the type of iterator used.

  • typeid, returns the type identification information at runtime.

  • iterator traits, defines the properties that iterator posses.

  • The iterator category is used to define the category to which they define iterator belongs.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
template <class T>
string iteratortype(T iterator){
   if (typeid(typename iterator_traits<T>::iterator_category)
      == typeid(input_iterator_tag))
      return "Input";
   else if (typeid(typename iterator_traits<T>::iterator_category)
      == typeid(output_iterator_tag))
      return "Output";
   else if (typeid(typename iterator_traits<T>::iterator_category)
      == typeid(forward_iterator_tag))
      return "Forward";
   else if (typeid(typename iterator_traits<T>::iterator_category)
      == typeid(bidirectional_iterator_tag))
      return "Bidirectional";
   else if (typeid(typename iterator_traits<T>::iterator_category)
      == typeid(random_access_iterator_tag))
      return "Random_Access";
   return "Missing";
int main(){
   vector<int> vec;
   auto iter = vec.begin();
   cout <<iteratortype(iter) << " Iterator
";    return 0; }


Random_Access Iterator
Updated on 19-Sep-2019 07:30:27