C++ push_front function
push_front is used in list toadds an element at the head of the linked listfunction; it is one of the characteristic operations of a linked list.
push_front is a member function, used tolinked list (list) 'sHeaderadd a new element.
Unlike vector,list inserting an element at the head has a time complexity of O(1), which is very efficient.
Word meaning: push is push,front is front; together they mean to push to the front, which is very intuitive.
Basic syntax and parameters
push_front is a member function of the container class; calling it requires no parameters.
Syntax format
void push_front(const T& value);
void push_front(T&& value); // C++11 之后(支持右值)
Parameter Description
- Parameters:
value - Type: Consistent with the element type specified when the container was defined
- Description: The value you want to add to the head of the container.
Function description
- Return Value:
void(No return value). - effect: The container's
size()increases by 1. The new element becomes the first element of the linked list.
Example
Let us thoroughly master push_front through a series of examples from simple to complex.
Example 1: Basic usage - add an element at the head
Example
#include
#include
int
main
(
)
{
std
::
list
<
int
numbers
=
{
20
,
30
,
40
};
std
::
cout
<<
"Original list: "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
// Add an element at the head
numbers.
push_front
(
10
)
;
std
::
cout
<<
"After push_front(10): "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
原始 list: 20 30 40
push_front(10) 后: 10 20 30 40
Code analysis:
push_front(10) Adds 10 to the head of the linked list, making it the first element.Example 2: Build a linked list
Use push_front can easily build a linked list from the head.
Example
#include
#include
int
main
(
)
{
std
::
list
<
int
data;
// Add at the head in sequence; the final order is the reverse of the addition order
data.
push_front
(
5
)
;
data.
push_front
(
4
)
;
data.
push_front
(
3
)
;
data.
push_front
(
2
)
;
data.
push_front
(
1
)
;
std
::
cout
<<
"Built linked list: "
;
for
(
int
n
:
data
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
构建的链表: 1 2 3 4 5
Code analysis:
- each time
push_frontadds the new element to the head. - The final linked list order is 1 -> 2 -> 3 -> 4 -> 5.
The C++ container class