Bidirectional Iterators in C++

C++Server Side ProgrammingProgramming

Here we will see the concept of Bidirectional iterators in C++.

  • The bidirectional iterators support all of the features of forward iterators, and also prefix and postfix decrement operators.
  • This type of iterator can access elements in both directions, like towards the end and towards the beginning.
  • The random access iterator is also a type of bidirectional iterator.
  • Bidirectional iterators have features of forward iterator, but only difference is this iterator can also be decremented.

The Bidirectional iterators has some properties. These are like below.

The bidirectional iterator is default-constructible, copy-assignable, and also destructibleA p
A q(p)
 q = p
We can compare them using equality and inequality operatorsp == q
 p != q
This can be dereferenced. We can use the dereference operator (*) to get value.*p
The mutable iterator can be dereferenced as lvalue*p = t
We can increment or decrement using increment operator (++), and decrement operator (--)p++

Example Code

#include <iostream>
using namespace std;
int main() {
   vector<int> vec{10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
   vector<int> ::iterator it;
   vector<int> :: reverse_iterator rev_it;
   for(it = vec.begin(); it != vec.end(); it++)
      cout<<*it<<" ";
      cout<< endl;
   for(rev_it = vec.rbegin(); rev_it!= vec.rend(); rev_it++)
      cout<<*rev_it<<" ";


10 20 30 40 50 60 70 80 90 100
100 90 80 70 60 50 40 30 20 10
Updated on 30-Jul-2019 22:30:26