forward_list
A forward_list
is a sequence container in C++ that allows efficient insertions and deletions at the front of the list. It stores a memory address to the first element, with each element containing data and a pointer to the next element. Compared to arrays, forward_list
offers faster insertions and deletions at the front but lacks direct access to elements by index.
Syntax
#include <forward_list>
std::forward_list<type> list_name;
type
: The type of the elements in theforward_list
. This can be any data type, such asint
,std::string
, or user-defined types.list_name
: The name of theforward_list
object being declared.
Note: To use
std::forward_list
, the header<forward_list>
must be included.
Example
The following example shows how to create a forward_list
and iterate over it:
#include <iostream>#include <forward_list>int main() {std::forward_list<int> list = {1,2,3,4,5};std::cout << "Output:" << std::endl;for(auto it = list.begin(); it != list.end(); ++it) {std::cout << *it << " ";}std::cout << std::endl;}
The output of the above program will be:
Output:1 2 3 4 5
Note: Unlike arrays,
forward_list
does not support direct access to elements through indices. To access a specific element, all preceding elements must be iterated over.
Codebyte Example
The following codebyte example demonstrates the use of forward_list
in C++ by initializing a list with elements, inserting an element at the front, removing an element from the front, and iterating over the list to print the remaining elements:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours