Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ container

C++ container

The C++ standard library's is a container that provides a singly linked list data structure.

Unlike a doubly linked list (std::list),std::forward_list only supports forward traversal. It is suitable for scenarios requiring frequent forward traversal and insertion/deletion operations. The following is a detailed explanation of std::forward_list :

Singly linked list:

Low memory overhead:

Does not support random access:

Syntax

std::forward_list is a template class in the C++ standard library, defined in the header. It uses the template parameter T to specify the type of elements stored in the list.

The following are std::forward_list 's basic syntax:

#include 



std::forward_list list;

constructor

std::forward_list provides several constructors, including:

Common member functions

Example

Below is an example using std::forward_list is a simple example, including creating a list, adding elements, traversing the list, and outputting results.

Example

#include

#include

int

main

(

)

{

   

// Create an empty forward_list

    std

::

forward_list

<

int

fl

;

   

// Add elements to the front of the list

    fl.

push_front

(

10

)

;

    fl.

push_front

(

20

)

;

    fl.

push_front

(

30

)

;

   

// Traverse the forward_list and output elements

   

for

(

auto

it

=

fl.

begin

(

)

;

it

!

=

fl.

end

(

)

;

++

it

)

{

        std

::

cout

<<

it

<<

" "

;

   

}

    std

::

cout

<<

std

::

endl

;

   

// Output: 30 20 10

   

return

0

;

}

When you run the code above, you will see the following output:

30 20 10

std::forward_list is a very useful container in the C++ standard library, especially suitable for scenarios requiring frequent insertion and deletion at the front of the list. Although it does not support random access, in some cases its performance advantage can compensate for this shortcoming. I hope this article helps beginners better understand and use std::forward_list.