C++ clear function
clear is used in list toclears all elementsfunction; it is the simplest and most efficient way to clear a container.
clear is a member function of the container class, used to remove all elements from the linked list, making it empty.
After calling it, the linked list's size() becomes 0.
Word meaning: clear means "clear," i.e., to remove all elements.
Basic syntax and parameters
clear is a member function of the container class; calling it requires no parameters.
Syntax format
void clear();
Function description
- Return Value:
void(No return value). - effect: Removes all elements from the linked list,
size()becomes 0.
Example
Example 1: Clear the linked list
Example
#include
#include
int
main
(
)
{
std
::
list
<
int
numbers
=
{
1
,
2
,
3
,
4
,
5
};
std
::
cout
<<
"Before clear - size: "
<<
numbers.
size
(
)
<<
std
::
endl
;
numbers.
clear
(
)
;
std
::
cout
<<
"After clear - size: "
<<
numbers.
size
(
)
<<
std
::
endl
;
return
0
;
}
Expected output:
清空前 - size: 5
清空后 - size: 0
Example 2: Reuse after clearing
Example
#include
#include
int
main
(
)
{
std
::
list
<
int
data;
data.
push_back
(
1
)
;
data.
push_back
(
2
)
;
std
::
cout
<<
"After first addition: "
<<
data.
size
(
)
<<
std
::
endl
;
data.
clear
(
)
;
data.
push_back
(
10
)
;
data.
push_back
(
20
)
;
data.
push_back
(
30
)
;
std
::
cout
<<
"After clearing and re-adding: "
;
for
(
int
n
:
data
)
std
::
cout
<<
n
<<
" "
;
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
第一次添加后: 2
清空后重新添加: 10 20 30
The C++ container class