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:
std::forward_listis a singly linked list that can only be traversed from front to back, not in reverse.- Due to its singly linked list structure, insertion and deletion are very efficient (O(1) complexity) when the position is known.
Low memory overhead:
- The difference between
std::listCompared tostd::forward_list, it only needs one pointer to the next node, saving memory.
Does not support random access:
- Does not support accessing elements by index; cannot use
operator[]oratmethod; can only be accessed via iterators.
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:
- Default constructor: creates an empty
forward_list. - Constructor with initial value: creates a with the given initial value
forward_list. - Range constructor: creates a with elements from the specified range
forward_list.
Common member functions
void push_front(const T& value): Inserts an element at the front of the list.void pop_front(): Removes the element at the front of the list.iterator before_begin(): Returns an iterator pointing before the front of the list.iterator begin(): Returns an iterator pointing to the front of the list.iterator end(): Returns an iterator pointing to the end of the list.
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.