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:
forward_list::begin() and forward_list::end() in C++ STL
Next article icon

Forward List in C++ STL

Last Updated : 28 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

C++
#include <iostream> #include <forward_list> using namespace std;  int main() {          // Create a forward list with 4 elements     forward_list<int> fl = {1, 5, 3, 4};      for (auto i : fl)          cout << i << " ";     return 0; } 

Output
1 5 3 4 

Explanation: In the above program, we created a forward list fl and initialized it with the 4 elements {1, 5, 3, 4}.

Syntax

Forward list is defined as std::forward_list class template inside the <forward_list> header file.

forward_list<T> fl;

where,

  • T: Data type of elements in the forward list.
  • fl: Name assigned to the forward list.

Declaration and Initialization

A forward_list can be declared and initialized in several ways as shown in the below example:

C++
#include <bits/stdc++.h> using namespace std;  void printFL(forward_list<int>& fl) {     for (auto i : fl)         cout << i << " ";     cout << '\n'; }  int main() {          // Creating an empty forward_list     forward_list<int> fl1;      // Creating a forward_list with     // default value     forward_list<int> fl2(3, 4);          // Creating a forward_list from an     // initializer list     forward_list<int> fl3 = {1, 5, 3, 4};          printFL(fl2);     printFL(fl3);     return 0; } 

Output
4 4 4  1 5 3 4  

Example: In the above program, we are simple initialized forward list in three ways:

  • Statement forward_list<int> fl1 creates an empty forward list of integers.
  • Statement forward_list<int> fl2(3,4) creates a forward list of size 3 and with each element being 4.
  • Statement forward_list<int> fl3 = {1, 5, 3, 4} creates a forward list and initializes with the elements form the initializer list.

Basic Operations

Here are the basic operations we can perform on a forward list:

1. Accessing Elements

Forward list’s elements cannot be accessed using indices like arrays or vectors. We have to go through the list sequentially from the start to the desired position to access it. This can be done by incrementing begin() iterator, but it is better to use next() or advance() function.

However, first element of the list can be easily accessed by front() method.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     forward_list<int> fl = {1, 5, 3, 4};      // Access the first element     cout << fl.front() << endl;          // Access third element     auto it = next(fl.begin(), 2);     cout << *it;     return 0; } 

Output
1 3

Example: In the above program, the first element is printed by using front() method. To access the third element, next() is used to move the iterator two positions from the beginning, and *it is used to dereference the iterator.

2. Inserting Elements

Elements can be inserted in the forward list using insert_after() function. It requires the iterator after which the element is to be inserted. However, fast insertion at the front is supported by push_front() method.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     forward_list<int> fl = {5, 4};      // Inserting Element at front     fl.push_front(1);          // Insert 3 after the second element     auto it = fl.begin();     advance(it, 1);     fl.insert_after(it, 3);          for (auto x: fl) cout << x << " ";     return 0; } 

Output
1 5 3 4 

Explanation: In this program, the first element of the forward_list is inserted at the front using the push_front() function. Then, an iterator is created and moved one position forward using the advance() function. After that, the element 5 is inserted after the second element using the insert_after() function.

3. Updating Elements

The value of existing elements can be changed simply by accessing them and using assignment operator to assign the new value.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     forward_list<int> fl = {1, 5, 3, 4};      // Updating first element     fl.front() = 111;     cout << fl.front() << endl;          // Updating third element     auto it = next(fl.begin(), 2);     *it = 333;     cout << *it;     return 0; } 

Output
111 333

4. Finding Element

The forward list does not provide any member function to search for an element, but we can use the find() algorithm to find any given value.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     forward_list<int> fl = {1, 5, 3, 4};      // Finding 3     auto it = find(fl.begin(), fl.end(), 3);          if (it != fl.end()) cout << *it;     else cout << "Element not Found";     return 0; } 

Output
3

5. Traversing

A forward list can be traversed using begin() and end() iterators with a loop, but we can only move forward and not backward.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     forward_list<int> fl = {1, 5, 3, 4};          // Traversing using range-based for loop     for(auto i : fl)         cout << i << " ";     cout << endl;          return 0; } 

Output
1 5 3 4  

6. Deleting Elements

In forward list, we can delete the element at the given position using erase_after() method. This method takes the iterator to one position before the target element. Fast deletion from the front is possible using pop_front() method.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     forward_list<int> fl = {1, 5, 3, 4};      // Delete first element     fl.pop_front();          // Delete third element     auto it = fl.begin();     advance(it, 1);     fl.erase_after(it);          for (auto x: fl) cout << x << " ";     return 0; } 

Output
5 3 

Time Complexity

The below table lists the time complexity of the above operations on forward list:

OperationTime Complexity
Access first elementO(1)
Access nth elementO(n)
Insert at frontO(1)
Insert after specific positionO(n)
Delete first elementO(1)
Delete after specific positionO(n)
TraversalO(n)

Other Common Operations

The following articles demonstrate some other operations that are commonly performed on a forward list container:

  • Check if Forward List is Empty
  • Find the Size of Forward List
  • Reverse Forward List
  • Sort Forward List
  • Merge Two Forward List
  • Swap Forward Lists
  • Create Forward List of Pairs

Internal Working

A forward list container provides the implementation of a singly linked list data structure. Each element in the list is stored in a node, which consists of two parts: the data and a pointer to the next node. The forward list maintains a pointer to the first node, known as the head, and the rest of the list contains the address of the next element in the sequence. This allows for fast insertion and deletion if the iterator to the element is known beforehand. But it sacrifices the random-access capability.

Forward List vs List

The key difference between a list and a forward list is given below:

  • Forward list is a singly linked list with only a pointer to the next element, allowing traversal in one direction.
  • List is a doubly linked list with pointers to both the next and previous elements, traversal in both directions.

All Member Functions

Following list cover all the functions of forward list:

Functions

Definition

front()This function is used to reference the first element of the forward list container.
begin()This function is used to return an iterator pointing to the first element of the forward list container.
end()This function is used to return an iterator pointing to the last element of the list container.
cbegin()Returns a constant iterator pointing to the first element of the forward_list.
cend()Returns a constant iterator pointing to the past-the-last element of the forward_list.
before_begin()Returns an iterator that points to the position before the first element of the forward_list.
cbefore_begin()Returns a constant iterator which points to the position before the first element of the forward_list.
max_size()Returns the maximum number of elements that can be held by forward_list.
resize()Changes the size of forward_list.
unique()Removes all consecutive duplicate elements from the forward_list. It uses a binary predicate for comparison.
reverse() Reverses the order of the elements present in the forward_list.

clear()

Remove all elements of the forward list.

insert_after()

Insert an element after a specific position.

emplace_after()

Constructs elements in-place after a specific position.

insert_range_after()

Insert range of elements after a specific position.

erase_after()

Delete the element just after a specific position.

push_front()

Add the new element at the beginning of the forward list.

emplace_front()

Constructs an element in-place at the beginning of the forward list.

pop_front()

Delete the top element of the forward list.

swap()

Swap the values of two forward list.

merge()

This function is used to merge sorted forward list into one.

unique()

Remove all consecutive duplicates elements from the forward list.

sort()

This function is used to sort the forward_list.

remove()

Remove all occurrence of the given value.

remove_if()

Remove all the values from the list that correspond true to the predicate or condition given as a parameter

empty()

Check forward list is empty or not.



Next Article
forward_list::begin() and forward_list::end() in C++ STL

M

Manjeet Singh
Improve
Article Tags :
  • C Language
  • C++
  • CPP-Library
  • STL
Practice Tags :
  • CPP
  • STL

Similar Reads

  • 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
  • Commonly Used Methods

    • forward_list::begin() and forward_list::end() in C++ STL
      Forward list in STL implements singly linked list. Introduced from C++11, the forward list is more useful than other containers in insertion, removal, and moving operations (like sort) and allows time constant insertion and removal of elements. It differs from list by the fact that the forward list
      3 min read

    • forward_list::push_front() and forward_list::pop_front() in C++ STL
      Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of
      4 min read

    • forward_list assign() function in C++ STL
      The forward_list::assign() is a function in C++ STL which assigns new content to a forward list, replacing its current content and adjusting its size as required.Syntax: Version 1:forward_list_name.assign(iterator it1, iterator it2) Version 2:forward_list_name.assign(int n, val) Version 3:forward_li
      2 min read

    • forward_list::front() and forward_list::empty() in C++ STL
      Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of
      3 min read

    • forward_list::remove() and forward_list::remove_if() in C++ STL
      Forward list in STL implements singly linked list. The forward list was introduced in C++11, and is useful than other containers in insertion, removal, and moving operations (like sort) and allows time constant insertion and removal of elements. It differs from the list by the fact that the forward
      4 min read

    • forward_list::clear() and forward_list::erase_after() in C++ STL
      Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of
      4 min read

    • forward_list::reverse() in C++ STL
      std::forward_list::reverse() is an inbuilt function in CPP STL which reverses the order of the elements present in the forward_list. Syntax: forwardlist_name.reverse()Parameter: The function does not accept any parameter. Return value: The function has no return value. It reverses the forward list.
      1 min read

    • forward_list::swap() in C++ STL
      The forward_list::swap() is a built-in function in CPP STL which exchanges the contents of the first given forward_list with another forward_list. Syntax: swap(forward_list first, forward_list second) or forward_list1.swap(forward_list second) Parameters: The function accepts two parameters which ar
      3 min read

    • std::forward_list::sort() in C++ STL
      Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of
      3 min read

    Other Member Methods

    • forward_list insert_after() function in C++ STL
      The forward_list::insert_after() is a builtin function in C++ STL which gives us a choice to insert elements at the position just after the element pointed by a given iterator in the forward list. The arguments in this function are copied at the desired position. Syntax: forward_list_name.insert_aft
      3 min read

    • forward_list::unique() in C++ STL
      forward_list::unique() is an inbuilt function in C++ STL which removes all consecutive duplicate elements from the forward_list. It uses binary predicate for comparison. Syntax: forwardlist_name.unique(BinaryPredicate name)Parameters: The function accepts a single parameter which is a binary predica
      2 min read

    • forward_list::cend() in C++ STL with Example
      forward_list::cend() is a function in C++ STL which returns a constant iterator pointing to the past-the-last element of the forward_list. The iterator returned by the function does not point to any element in the container, but to the position followed by the last element of the forward list contai
      2 min read

    • forward_list emplace_after() and emplace_front() in C++ STL
      The forward_list::emplace_after() is a builtin function in C++ STL which is used to insert a new element after the element at position specified in the argument. This insertion of the new element increases the size of the container by one. Syntax: forward_list_name.emplace_after(iterator position, e
      2 min read

    • forward_list resize() function in C++ STL
      The forward_list::resize() is an inbuilt function in C++ STL which changes the size of forward_list. If the given size is greater than the current size then new elements are inserted at the end of the forward_list. If the given size is smaller than current size then extra elements are destroyed. Syn
      2 min read

    • forward_list::splice_after() in C++ STL
      forward_list::splice_after() is an inbuilt function in CPP STL which transfers the elements in the range of first+1 to last from a given forward_list to another forward_list. The elements are inserted after the element pointed to by position in the parameter. Syntax: forwardlist1_name.splice_after(p
      2 min read

    • forward_list cbegin() in C++ STL
      The forward_list::cbegin() is a function in C++ STL which returns a constant iterator pointing to the first element of the forward_list. Syntax: forward_list_name.cbegin() Parameters: This function does not accept any parameter. Return Value: This function returns an iterator that points to the cons
      2 min read

    • forward_list::max_size() in C++ STL
      std::forward_list::max_size() is an inbuilt function in CPP STL which returns the maximum number of elements can be held by forward_list. This value depends on system or library implementation. Syntax: forwardlist_name.max_size ()Parameters: The function does not accept any parameters. Return value:
      1 min read

    • forward_list::before_begin() in C++ STL
      forward_list::before_begin() is an inbuilt function in C++ STL that returns an iterator that points to the position before the first element of the forward_list. Forward list in STL is a singly linked list implementation. This function comes under the <forward_list> header file. Syntax: forwar
      1 min read

    • forward_list::cbefore_begin() in C++ STL
      forward_list::cbefore_begin() is an inbuilt function in CPP STL which returns a constant random access iterator which points to the position before the first element of the forward_list. The iterator obtained by this function can be used to iterate in the container but cannot be used to modify the c
      2 min read

    • forward_list merge() in C++ STL
      forward_list::merge() is an inbuilt function in C++ STL which merges two sorted forward_lists into one. The merge() function can be used in two ways: Merge two forward lists that are sorted in ascending order into one. Merge two forward lists into one using a comparison function. Syntax: forwardlist
      2 min read

  • Forward List and List of Pairs in C++ with Examples
    Forward List Forward list in STL implements singly linked list. Introduced from C++11, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differs from the list by the fact that the
    8 min read
  • Forward List and List of Tuples in C++ with Examples
    What is Forward List? Forward list in STL is used to implement a singly linked list. It was introduced from C++11 onwards, forward lists are more useful than other containers in insertion, removal, and moving operations (like sort) and allow time constant insertion and removal of elements. It differ
    9 min read
  • Difference Between Forward List and List in C++
    Forward List is a sequence container that allows unidirectional sequential access to its data. It contains data of the same type. In STL, it has been implemented using Singly Linked List, which requires constant time for insertion and deletion. Elements of the forward list are scattered in the memor
    3 min read
  • Common Forward List Programs

    • How to find Size of std::forward_list in C++ STL
      Forward list in standard template library of C++. It comes under #include<forward_list> header file. It is implemented as a singly linked list. It was introduced in C++ 11 for the first time. Forward lists are sequence containers that allow constant time insert and erase operations from anywhe
      3 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