C++ pop_back function
pop_back is used in list toremoves the last element of the linked list.
pop_back is a member function of the container class, used to remove the last element of the linked list.
In list,pop_back has a time complexity of O(1), which is very efficient.
Word meaning: pop is pop,back is back; together they mean to pop the element at the back.
Basic syntax and parameters
pop_back is a member function of the container class; calling it requires no parameters.
Syntax format
void pop_back();
Parameter Description
- Parameters: No parameters
Function description
- Return Value:
void(No return value). - effect: The container's
size()decreases by 1. The last element is removed. - Note: If the linked list is empty, calling
pop_backis undefined behavior.
Example
Example 1: Basic usage - remove the last 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 last element
numbers.
pop_back
(
)
;
std
::
cout
<<
"After pop_back(): "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
numbers.
pop_back
(
)
;
std
::
cout
<<
"After another pop_back(): "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
原始 list: 10 20 30 40 50
pop_back() 后: 10 20 30 40
再 pop_back() 后: 10 20 30
Example 2: Safe use of pop_back
Check whether the linked list is empty before use.
Example
#include
#include
void
safePopBack
(
std
::
list
<
int
&
lst
)
{
if
(!
lst.
empty
(
)
)
{
lst.
pop_back
(
)
;
std
::
cout
<<
"Deletion succeeded"
<<
std
::
endl
;
}
else
{
std
::
cout
<<
"Linked list is empty; cannot delete"
<<
std
::
endl
;
}
}
int
main
(
)
{
std
::
list
<
int
data
=
{
1
,
2
,
3
};
safePopBack
(
data
)
;
safePopBack
(
data
)
;
safePopBack
(
data
)
;
safePopBack
(
data
)
;
// It is empty at this point
return
0
;
}
Expected output:
删除成功
删除成功
删除成功
链表为空,无法删除
The C++ container class