C++ Containers<forward_list>
In the C++ standard library's<forward_list>Is a container that provides a singly linked list data structure.
with doubly linked list (std::list) different,std::forward_listOnly supports forward traversal. It is suitable for scenarios that require frequent forward traversal and insertion/deletion operations. The following is aboutstd::forward_listdetailed description:
Singly Linked List:
std::forward_listIs a singly linked list, can only be traversed from front to back, not in reverse.- Due to its singly linked list structure, insertion and deletion operations are very efficient when the position is known (O(1) complexity).
Low memory overhead:
- and
std::listIn comparison,std::forward_listOnly needs a 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 through iterators.
Syntax
std::forward_listIs a template class in the C++ standard library, defined in<forward_list>header file. It uses template parametersTto specify the type of elements stored in the list.
The following arestd::forward_listbasic syntax:
#include <forward_list> std::forward_list<T> list;
Constructor
std::forward_listProvides multiple constructors, including:
- Default constructor: creates an empty
forward_list。 - Constructor with initial values: creates a [container] containing the given initial values.
forward_list。 - Range constructor: creates a [container] containing the elements in the specified range.
forward_list。
commonly used 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 usingstd::forward_listA simple example, including creating a list, adding elements, traversing the list, and outputting the results.
Example
#include <forward_list>
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);
// iterate through the forward_list and output elements
for (auto it = fl.begin(); it != fl.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// output result: 30 20 10
return 0;
}
When you run the above code, you will see the following output:
30 20 10
std::forward_listis a very useful container in the C++ standard library, particularly suitable for scenarios that require frequent insertions and deletions at the front of the list. Although it does not support random access, in certain cases, its performance advantages can compensate for this shortcoming. I hope this article can help beginners better understand and use it.std::forward_list。