Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
Output Iterators in C++
Next article icon

Forward Iterators in C++

Last Updated : 25 Apr, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

After going through the template definition of various STL algorithms like std::search, std::search_n, std::lower_bound, you must have found their template definition consisting of objects of type Forward Iterator. So what are they and why are they used ?

Forward iterators are one of the five main types of iterators present in C++ Standard Library, others being Input iterators, Output iterator, Bidirectional iterator and Random – access iterators.

Forward iterators are considered to be the combination of input as well as output iterators. It provides support to the functionality of both of them. It permits values to be both accessed and modified.

One important thing to be kept in mind is that bidirectional and random-access iterators are also valid forward iterators, as shown in the iterator hierarchy above.

Salient Features

  1. Usability: Performing operations on a forward iterator that is dereferenceable never makes its iterator value non-dereferenceable, as a result this enables algorithms that use this category of iterators to use multiple copies of an iterator to pass more than once by the same iterator values. So, it can be used in multi-pass algorithms.
  2. Equality / Inequality Comparison: A forward iterator can be compared for equality with another iterator. Since, iterators point to some location, so the two iterators will be equal only when they point to the same position, otherwise not.

    So, the following two expressions are valid if A and B are forward iterators:

      A == B  // Checking for equality  A != B  // Checking for inequality  
  3. Dereferencing: Because an input iterator can be dereferenced, using the operator * and -> as an rvalue and an output iterator can be dereferenced as an lvalue, so forward iterators can be used for both the purposes.




    // C++ program to demonstrate forward iterator
    #include <iostream>
    #include <vector>
    using namespace std;
    int main()
    {
        vector<int> v1 = { 1, 2, 3, 4, 5 };
      
        // Declaring an iterator
        vector<int>::iterator i1;
      
        for (i1 = v1.begin(); i1 != v1.end(); ++i1) {
            // Assigning values to locations pointed by iterator
            *i1 = 1;
        }
      
        for (i1 = v1.begin(); i1 != v1.end(); ++i1) {
            // Accessing values at locations pointed by iterator
            cout << (*i1) << " ";
        }
      
        return 0;
    }
     
     

    Output:

      1 1 1 1 1  

    So, as we can see here we can both access as well as assign value to the iterator, therefore the iterator is at least a forward iterator( it can be higher in hierarchy also).

  4. Incrementable: A forward iterator can be incremented, so that it refers to the next element in sequence, using operator ++().

    Note: The fact that we can use forward iterators with increment operator doesn’t mean that operator – -() can also be used with them. Remember, that forward iterators are unidirectional and can only move in the forward direction.

    So, the following two expressions are valid if A is a forward iterator:

      A++   // Using post increment operator  ++A   // Using pre increment operator  
  5. Swappable: The value pointed to by these iterators can be exchanged or swapped.

Practical implementation

After understanding its features, it is very important to learn about its practical implementation as well. As told earlier, forward iterators can be used both when we want to access elements and also when we have to assign elements to them, as it is the combination of both input and output iterator. The following two STL algorithms can show this fact:

  • std::replace: As we know this algorithm is used to replace all the elements in the range which are equal to a particular value by a new value. So, let us look at its internal working (Don’t go into detail just look where forward iterators can be used and where they cannot be):




    // Definition of std::replace()
    template void replace(ForwardIterator first, ForwardIterator last,
                          const T& old_value, const T& new_value)
    {
        while (first != last) {
            if (*first == old_value) // L1
                *first = new_value; // L2
            ++first;
        }
    }
     
     

    Here, we can see that we have made use of forward iterators, as we need to make use of the feature of both input as well as output iterators. In L1, we are required to dereference the iterator first as a rvalue (input iterator) and in L2, we are required to dereference first as a lvalue (output iterator), so to accomplish both the tasks, we have made use of forward iterators.

  • std::reverse_copy: As the name suggests, this algorithm is used to copy a range into another range, but in reverse order. Now, as far as accessing elements and assigning elements are concerned, forward iterators are fine, but as soon as we have to decrement the iterator, then we cannot use these forward iterators for this purpose.




    // Definition of std::reverse_copy()
    template OutputIterator reverse_copy(BidirectionalIterator first,
                                         BidirectionalIterator last,
                                         OutputIterator result)
    {
        while (first != last)
            *result++ = *--last;
        return result;
    }
     
     

    Here, we can see that we have declared last as a bidirectional iterator, and not a forward iterator since we cannot decrement a forward iterator as done in case of last, so we cannot use it in this scenario.

Note: As we know that forward iterators are the combination of both input and output iterators, so if any algorithm involves the use of any of these two iterators, then we can use forward iterators in their place as well, without affecting the program.

So, the two above examples very well show when, where, why and how forward iterators are used practically.

Limitations

After studying the salient features, one must also know its deficiencies as well although there are not as many as there are in input or output iterators as it is higher in the hierarchy.

  1. Can not be decremented: Just like we can use operator ++() with forward iterators for incrementing them, we cannot decrement them. Although it is higher in the hierarchy than input and output iterators, still it can’t overcome this deficiency.

    That is why, its name is forward, which shows that it can move only in forward direction.

      If A is a forward iterator, then    A--    // Not allowed with forward iterators  
  2. Relational Operators: Although, forward iterators can be used with equality operator (==), it can not be used with other relational operators like =.
      If A and B are forward iterators, then    A == B     // Allowed  A <= B     // Not Allowed  
  3. Arithmetic Operators: Similar to relational operators, they also can’t be used with arithmetic operators like +, – and so on. This means that forward operators can only move in one direction that too forward and that too sequentially.
      If A and B are forward iterators, then    A + 1     // Not allowed  B - 2     // Not allowed  
  4. Use of offset dereference operator ([ ]): Forward iterators do not support offset dereference operator ([ ]), which is used for random-access.
      If A is a forward iterator, then  A[3]    // Not allowed   


Next Article
Output Iterators in C++
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • C++
  • Misc
  • cpp-iterator
  • STL
Practice Tags :
  • CPP
  • Misc
  • STL

Similar Reads

  • C++ Standard Template Library (STL)
    The C++ Standard Template Library (STL) is a set of template classes and functions that provides the implementation of common data structures and algorithms such as lists, stacks, arrays, sorting, searching, etc. It also provides the iterators and functors which makes it easier to work with algorith
    9 min read
  • Containers in C++ STL
    Standard Template Library (STL) provides the built-in implementation of commonly used data structures known as containers. A container is a holder object that stores a collection of other objects (its elements). They are implemented as class templates, which allows great flexibility in the data type
    3 min read
  • STL Containers

    • STD::array in C++
      The array is a collection of homogeneous objects and this array container is defined for constant size arrays or (static size). This container wraps around fixed-size arrays and the information of its size are not lost when declared to a pointer. In order to utilize arrays, we need to include the ar
      5 min read

    • Vector in C++ STL
      C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted. Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template
      8 min read

    • List in C++ STL
      In C++, list container implements a doubly linked list in which each element contains the address of next and previous element in the list. It stores data in non-contiguous memory, hence providing fast insertion and deletion once the position of the element is known. Example: [GFGTABS] C++ #include
      8 min read

    • Forward List in C++ STL
      In C++, forward_list container provides the implementation of singly linked list data structure. It stores data in non-contiguous memory where each element points to the next element in the sequence. This makes insertion and deletion faster once the position of the element is known. Example: [GFGTAB
      8 min read

    • Stack in C++ STL
      In C++, stack container follows LIFO (Last In First Out) order of insertion and deletion. It means that most recently inserted element is removed first and the first inserted element will be removed last. This is done by inserting and deleting elements at only one end of the stack which is generally
      5 min read

    • Queue in C++ STL
      In C++, queue container follows the FIFO (First In First Out) order of insertion and deletion. According to it, the elements that are inserted first should be removed first. This is possible by inserting elements at one end (called back) and deleting them from the other end (called front) of the dat
      5 min read

    • Deque in C++ STL
      In C++, deque container provides fast insertion and deletion at both ends. Stands for Double Ended QUEue, it is a special type of queue where insertion and deletion operations are possible at both the ends in constant time complexity. Example: [GFGTABS] C++ #include <iostream> #include <deq
      7 min read

    • Set in C++ STL
      In C++, sets are associative container which stores unique elements in some sorted order. By default, it is sorted ascending order of the keys, but this can be changed as per requirement. It provides fast insertion, deletion and search operations. Example: [GFGTABS] C++ #include <iostream> #in
      7 min read

    • Map in C++ STL
      In C++, maps are associative containers that store data in the form of key value pairs sorted on the basis of keys. No two mapped values can have the same keys. By default, it stores data in ascending order of the keys, but this can be changes as per requirement. Example: [GFGTABS] C++ #include <
      8 min read

    • Multiset in C++ STL
      In C++, multiset is an associative container similar to the set, but it can store multiple elements with same value. It is sorted in increasing order by default, but it can be changed to any desired order. It provides fast insertion, deletion and search operations. Example: [GFGTABS] C++ #include
      7 min read

    • Multimap in C++ STL
      In C++, multimap is an associative container similar to map, but it can have multiple elements with same keys. It stores all the elements in increasing order based on their keys by default but can be changed if required. It provides fast insertion, deletion and search on this sorted data. Example: [
      8 min read

    • Unordered Sets in C++ STL
      In C++, unordered_set is an unordered associative container that stores unique elements. Unlike set, it stores its elements using hashing. This provides average constant-time O(1) search, insert, and delete operations but the elements are not sorted in any particular order. Example: [GFGTABS] C++ #i
      7 min read

    • Unordered Map in C++ STL
      In C++, unordered_map is an unordered associative container that stores data in the form of unique key-value pairs. But unlike map, unordered map stores its elements using hashing. This provides average constant-time complexity O(1) for search, insert, and delete operations but the elements are not
      8 min read

    • Unordered Multiset in C++ STL
      In C++, unordered multiset is an unordered associative container that works similarly to an unordered set, but it can store multiple copies of the same value. It provides fast insert, delete and search operations using hashing, but the elements are not in any particular order. Example: [GFGTABS] C++
      7 min read

    • Unordered Multimap in C++ STL
      In C++, the unordered_multimap is an unordered associative container that stores data in the form of key-value pairs. It is similar to unordered map, but it allows multiple elements with the same key. It provides fast insertion, deletion and search operations in O(1) time by using hashing. Example:
      8 min read

  • Introduction to Iterators in C++
    An iterator is an object like a pointer that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualized as something similar to a pointer pointing to some location and we can access the content at that particular location usi
    4 min read
  • STL Iterators

    • Forward Iterators in C++
      After going through the template definition of various STL algorithms like std::search, std::search_n, std::lower_bound, you must have found their template definition consisting of objects of type Forward Iterator. So what are they and why are they used ? Forward iterators are one of the five main t
      6 min read

    • Output Iterators in C++
      After going through the template definition of various STL algorithms like std::copy, std::move, std::transform, you must have found their template definition consisting of objects of type Output Iterator. So what are they and why are they used ? Output iterators are one of the five main types of it
      6 min read

    • Forward Iterators in C++
      After going through the template definition of various STL algorithms like std::search, std::search_n, std::lower_bound, you must have found their template definition consisting of objects of type Forward Iterator. So what are they and why are they used ? Forward iterators are one of the five main t
      6 min read

    • Bidirectional Iterators in C++
      After going through the template definition of various STL algorithms like std::reverse, std::next_permutation and std::reverse_copy you must have found their template definition consisting of objects of type Bidirectional Iterator. So what are they and why are they used ? Bidirectional iterators ar
      7 min read

    • Random Access Iterators in C++
      After going through the template definition of various STL algorithms like std::nth_element, std::sort, you must have found their template definition consisting of objects of type Random-access Iterator. So what are they and why are they used?Random-access iterators are one of the five main types of
      6 min read

    • Iterators in C++ STL
      An iterator in C++ is a pointer-like object that points to an element of the STL container. They are generally used to loop through the contents of the STL container in C++. The main advantage of STL iterators is that they make the STL algorithms independent of the type of container used. We can jus
      11 min read

  • C++ STL Algorithm Library
    Standard Template Library (STL) offers a rich collection of algorithms designed to operate on STL containers and beyond. It provides commonly used algorithms such as sorting, searching, copying, etc. These well tested algorithms are optimized for performance and provide a way to write cleaner, faste
    4 min read
  • STL Algorithms

    • sort() in C++ STL
      In C++, sort() is a built-in function used to sort the given range in desired order. It provides a simple and efficient way to sort the data in C++, but it only works on data structures that provide random access to its elements such as vectors and arrays. Let's take a look at an example: [GFGTABS]
      4 min read

    • Different methods to copy in C++ STL | std::copy(), copy_n(), copy_if(), copy_backward()
      Various varieties of copy() exist in C++ STL that allows to perform the copy operations in different manners, all of them having their own use. These all are defined in header <algorithm>. This article introduces everyone to these functions for usage in day-to-day programming. 1. copy(strt_ite
      5 min read

    • max_element in C++ STL
      The std::max_element() in C++ is an STL algorithm that is used to find the maximum element in the given range. It is defined inside the <algorithm> header file. In this article, we will learn how to find the maximum element in the range using std::max_element() in C++. Example: [GFGTABS] C++ /
      4 min read

    • find() in C++ STL
      C++ find() is a built-in function used to find the first occurrence of an element in the given range. It works with any container that supports iterators, such as arrays, vectors, lists, and more. In this article, we will learn about find() function in C++. [GFGTABS] C++ //Driver Code Starts{ #inclu
      2 min read

    • for_each loop in C++
      Apart from the generic looping techniques, such as "for, while and do-while", C++ in its language also allows us to use another functionality which solves the same purpose termed "for-each" loops. This loop accepts a function which executes over each of the container elements. This loop is defined i
      5 min read

    • Algorithm Library Functions in C++ STL
      Non-modifying sequence operations std :: all_of : Test condition on all elements in rangestd :: any_of : Test if any element in range fulfills conditionstd :: none_of : Test if no elements fulfill conditionstd :: for_each : Apply function to rangestd :: find : Find value in rangestd :: find_if : Fin
      4 min read

  • Functors in C++
    Please note that the title is Functors (Not Functions)!! Consider a function that takes only one argument. However, while calling this function we have a lot more information that we would like to pass to this function, but we cannot as it accepts only one parameter. What can be done? One obvious an
    3 min read
  • C++ STL Cheat Sheet
    The C++ STL Cheat Sheet provides short and concise notes on Standard Template Library (STL) in C++. Designed for programmers that want to quickly go through key STL concepts, the STL cheatsheet covers the concepts such as vectors and other containers, iterators, functors, etc., with their syntax and
    15+ min read
  • Top C++ STL Interview Questions and Answers
    The Standard Template Library (STL) is a set of C++ template classes that are used to implement widely popular algorithms and data structures such as vectors, lists, stacks, and queues. It is part of the C++ Language ISO standard. STL is a popular topic among interviewers, so it is useful for both f
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences