c-plus-plus
  1. c-plus-plus-bidirectional-iterator

C++ Iterators: Bidirectional Iterator

A bidirectional iterator is a type of C++ iterator that can be used to traverse a collection or container of elements in both directions - forward and backward.

Syntax

#include <iterator>

std::bidirectional_iterator_tag

The bidirectional iterator is defined as part of the header file in C++.

Example

#include <iostream>
#include <list>

int main() {
    std::list<int> mylist = { 1, 2, 3, 4, 5 };
    std::list<int>::iterator it = mylist.begin();

    // iterate forward
    while (it != mylist.end()) {
        std::cout << *it << " ";
        it++;
    }
    std::cout << std::endl;

    // iterate backward
    while (it != mylist.begin()) {
        it--;
        std::cout << *it << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output

1 2 3 4 5 
5 4 3 2 1 

Explanation

In the above example, we have a list of integers and we use a bidirectional iterator to traverse it first in the forward direction and then in the backward direction.

To iterate forward, we start at the beginning of the list using the begin() function and iterate until we reach the end of the list using the end() function.

To iterate backward, we simply decrement the iterator using the -- operator.

Use

Bidirectional iterators are useful when you need to traverse a collection or container in both directions, such as when implementing data structures like doubly linked lists.

Important Points

  • Bidirectional iterators can be used to traverse a collection or container in both directions - forward and backward.
  • They are part of the header file in C++.
  • Iterators can be incremented using the ++ operator and decremented using the -- operator.

Summary

In summary, bidirectional iterators in C++ are used to traverse collections or containers in both directions - forward and backward. They are useful when you need to implement data structures like doubly linked lists. Bidirectional iterators are defined in the header file and can be incremented or decremented using the ++ or -- operator.

Published on: