C++ pop_front function
pop_front is used in list toremoves the first element of the linked listfunction; it is one of the characteristic operations of a linked list.
pop_front is a member function of the container class, used to remove the first element of the linked list.
Unlike vector,list deleting an element at the head has a time complexity of O(1), which is very efficient.
Word meaning: pop is pop,front is front; together they mean to pop the element at the front.
Basic syntax and parameters
pop_front is a member function of the container class; calling it requires no parameters.
Syntax format
void pop_front();
Parameter Description
- Parameters: No parameters
Function description
- Return Value:
void(No return value). - effect: The container's
size()decreases by 1. The first element is removed. - Note: If the linked list is empty, calling
pop_frontis undefined behavior.
Example
Example 1: Basic usage - remove the head element
Example
#include
#include
int
main
(
)
{
std
::
list
<
int
numbers
=
{
10
,
20
,
30
,
40
,
50
};
std
::
cout
<<
"Original list: "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
// Remove the head element
numbers.
pop_front
(
)
;
std
::
cout
<<
"After pop_front(): "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
numbers.
pop_front
(
)
;
std
::
cout
<<
"After another pop_front(): "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
原始 list: 10 20 30 40 50
pop_front() 后: 20 30 40 50
再 pop_front() 后: 30 40 50
Example 2: Implement a queue
Use push_back and pop_front can be used to implement a queue.
Example
#include
#include
#include
class
Queue
{
private
:
std
::
list
<
std
::
string
data
;
public
:
void
enqueue
(
const
std
::
string
&
item
)
{
data.
push_back
(
item
)
;
}
void
dequeue
(
)
{
if
(
!
data.
empty
(
)
)
{
data.
pop_front
(
)
;
}
}
std
::
string
front
(
)
const
{
return
data.
front
(
)
;
}
bool
empty
(
)
const
{
return
data.
empty
(
)
;
}
size_t
size
(
)
const
{
return
data.
size
(
)
;
}
}
;
int
main
(
)
{
Queue q
;
q.
enqueue
(
"UserA"
)
;
q.
enqueue
(
"UserB"
)
;
q.
enqueue
(
"UserC"
)
;
std
::
cout
<<
"Queue size: "
<<
q.
size
(
)
<<
std
::
endl
;
while
(
!
q.
empty
(
)
)
{
std
::
cout
<<
"Processing: "
<<
q.
front
(
)
<<
std
::
endl
;
q.
dequeue
(
)
;
}
return
0
;
}
Expected output:
队列大小: 3
处理: 用户A
处理: 用户B
处理: 用户C
The C++ container class