C++ size() function
size is one of the most commonly used functions in list, used toget the number of elements in the linked list.
size is a member function of the container class, used to return the current number of elements in the linked list.
Unlike vector, list's size() is usually completed in O(1) time.
Word meaning: size means "size," indicating the number of elements in the linked list.
Basic syntax and parameters
Syntax format
size_type size() const;
Function description
- Return Value: Returns the number of elements in the linked list (
size_type).
Example
Example 1: Get the linked list size
Example
#include
#include
int
main
(
)
{
std
::
list
<
int
empty;
std
::
cout
<<
"Empty list size: "
<<
empty.
size
(
)
<<
std
::
endl
;
std
::
list
<
int
numbers
=
{
1
,
2
,
3
,
4
,
5
};
std
::
cout
<<
"5-element list size: "
<<
numbers.
size
(
)
<<
std
::
endl
;
numbers.
push_back
(
6
)
;
std
::
cout
<<
"Size after adding: "
<<
numbers.
size
(
)
<<
std
::
endl
;
return
0
;
}
Expected output:
空链表 size: 0
5元素链表 size: 5
添加后 size: 6
The C++ container class