C++ erase function
erase is used in list toremoves the element at a specified position.
erase is a member function of the container class, used to remove one or more elements at a specified position in the linked list.
In list,erase has a time complexity of O(1), because only pointers need to be adjusted.
Word meaning: erase means "erase," i.e., to remove the element at the specified position.
Basic syntax and parameters
erase is a member function of the container class.
Syntax format
iterator erase(iterator pos);
iterator erase(iterator first, iterator last);
Parameter Description
- Parameters:
pos- Position of the element to delete - Parameters:
first, last- Range of elements to delete
Function description
- Return Value: Returns an iterator pointing to the next element.
- effect: Removes the element at the specified position.
Example
Example 1: Delete a single element
Example
#include
#include
int
main
(
)
{
std
::
list
<
int
numbers
=
{
1
,
2
,
3
,
4
,
5
};
std
::
cout
<<
"Original: "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
// Delete the second element
auto
it
=
std
::
next
(
numbers.
begin
(
)
,
1
)
;
numbers.
erase
(
it
)
;
std
::
cout
<<
"After deletion: "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
原始: 1 2 3 4 5
删除后: 1 3 4 5
Example 2: Delete multiple elements
Example
#include
#include
int
main
(
)
{
std
::
list
<
int
numbers
=
{
1
,
2
,
3
,
4
,
5
,
6
,
7
};
std
::
cout
<<
"Original: "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
// Delete the 2nd through 4th elements
auto
first
=
std
::
next
(
numbers.
begin
(
)
,
1
)
;
auto
last
=
std
::
next
(
numbers.
begin
(
)
,
4
)
;
numbers.
erase
(
first, last
)
;
std
::
cout
<<
"After deletion: "
;
for
(
int
n
:
numbers
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
原始: 1 2 3 4 5 6 7
删除后: 1 5 6 7
The C++ container class