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-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
a->m
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
a++
*a++
Can be decremented (if a dereferenceable iterator value precedes it).--a
a--
*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

Example

#include <iostream>
#include<iterator>
#include<vector>
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<<" ";
}

Output

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