C++ Bidirectional Iterators

C++Server Side ProgrammingProgramming

The iterators that have the privilege to access the sequence of elements of a range from both the directions that are from the end and from the beginning are known as bidirectional iterators. iterators can work on data types like list map and sets.

Bidirectional iterators have the same properties as forwarding iterators, with the only difference that they can also be decremented −

propertyvalid expressions
Is default-constructible,
copy-assignable and destructible
X a;
X b(a);
b = a;
Can be compared for equivalence using the equality/inequality operators (meaningful when both iterator values iterate over the same underlying sequence).a == b
a != b
Can be dereferenced as an rvalue (if in a dereferenceable state).*a
For mutable iterators (non-constant iterators): Can be dereferenced as an lvalue (if in a dereferenceable state).*a = t
Can be incremented (if in a dereferenceable state). The result is either also dereferenceable or a past-the-end iterator. Two iterators that compare equal, keep comparing equal after being both increased.++a
Can be decremented (if a dereferenceable iterator value precedes it).--a
Lvalues are swappable.swap(a,b)

Where X is a bidirectional iterator, a and b are objects of this iterator type, and t is an object of the type pointed by the iterator type (or some other type that can be assigned to the lvalue returned by dereferencing an object of type X).

The concept of Bidirectional iterators in C++.

  • The bidirectional iterators support all of the features of forwarding 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 forwarding iterator, but the only difference is this iterator can also be decremented.

Input: 1 2 3 4 5 6 7 8 9 10
Output: 10 9 8 7 6 5 4 3 2 1


#include <iostream>
using namespace std;
int main() {
   vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   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<<" ";


1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
Updated on 19-Aug-2019 08:07:41