c-plus-plus
  1. c-plus-plus-forward-iterator

C++ Iterators: Forward Iterator

An iterator is a C++ object that can traverse through the elements of a container class like an array, vector, or list. In C++, there are many types of iterators, each with its own specific use. The forward iterator is one such type of iterator.

Syntax

forward_iterator_type iterator_name;

Where "forward_iterator_type" is the type of the iterator, and "iterator_name" is the name of the iterator.

Example

#include <iostream>
#include <forward_list>
using namespace std;

int main() {
    forward_list<int> numbers;
    numbers.push_front(10);
    numbers.push_front(20);
    numbers.push_front(30);
    
    forward_list<int>::iterator it;
    for(it = numbers.begin(); it != numbers.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;
    return 0;
}

Output

30 20 10

Explanation

In the above example, we have defined a forward list called "numbers" and added three integers to it. We then created an iterator of type "forward_list::iterator" called "it". We used a for loop to iterate through the list using the iterator and printed out its elements.

Use

The forward iterator is used to iterate through a container in a forward direction, from the beginning to the end. This type of iterator is useful for traversing linked lists, where elements are connected in a linear sequence.

Important Points

  • The forward iterator can only traverse through a container in a forward direction.
  • Its main use is with linked lists, where elements are connected in a linear sequence.
  • The forward iterator is a single-pass iterator, meaning it can only be used to traverse a container once.

Summary

In summary, the forward iterator is a type of iterator that is used to traverse through a container in a forward direction. It is useful for linked lists, where elements are connected in a linear sequence. The forward iterator is a single-pass iterator and can only be used to traverse a container once.

Published on: