C++ size() function
size is one of the most commonly used and fundamental functions in array, used toget the number of elements in the container.
size is a member function of the container class, used toreturns the current number of elements in the container. Unlike vector, array's size is fixed and determined at compile time.
size is the most frequently used function when operating on array, used in scenarios such as loop traversal and bounds checking.
Word meaning: size means 'size', i.e., the number of elements in the container.
Basic syntax and parameters
size is a member function of the container class; calling it requires no parameters.
Syntax format
constexpr size_type size() const noexcept;
Parameter Description
- Parameters: No parameters
sizetakes no arguments.
Function description
- Return Value: Returns
size_typetype (usuallysize_t), representing the number of elements in the container. - effect: Returns a non-negative integer representing the fixed number of elements stored in the container.
- Note:
size()returns a compile-time constant (constexpr) that can be used at compile time.
Example
Let us thoroughly master size through a series of examples from simple to complex.
Example 1: Basic usage - getting the number of elements
Example
#include
#include
int
main
(
)
{
// Arrays of different sizes
std
::
array
<
int
,
3
small
=
{
1
,
2
,
3
};
std
::
array
<
int
,
5
medium
=
{
1
,
2
,
3
,
4
,
5
};
std
::
array
<
int
,
10
large
=
{
};
std
::
cout
<<
"small array size: "
<<
small.
size
(
)
<<
std
::
endl
;
std
::
cout
<<
"medium array size: "
<<
medium.
size
(
)
<<
std
::
endl
;
std
::
cout
<<
"large array size: "
<<
large.
size
(
)
<<
std
::
endl
;
return
0
;
}
Expected output:
small array 大小: 3
medium array 大小: 5
large array 大小: 10
Code analysis:
- array's size is determined at compile time and specified by the template parameter.
size()returns exactly this compile-time-determined value.
Example 2: Using size() in a loop
size() is most commonly used to control loop traversal.
Example
#include
#include
int
main
(
)
{
std
::
array
<
int
,
5
numbers
=
{
10
,
20
,
30
,
40
,
50
};
// Use size() to control the loop
std
::
cout
<<
"Traverse all elements: "
;
for
(
size_t
i
=
0
;
i
<
numbers.
size
(
)
;
++
i
)
{
std
::
cout
<<
numbers
[
i
]
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
// Use size() to get the boundary for reverse traversal
std
::
cout
<<
"Reverse traversal: "
;
for
(
size_t
i
=
numbers.
size
(
)
;
i
0
;
--
i
)
{
std
::
cout
<<
numbers
[
i
1
]
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
遍历所有元素: 10 20 30 40 50
反向遍历: 50 40 30 20 10
Code analysis:
numbers.size()returns 5, and the loop conditioni < numbers.size()ensures no out-of-bounds access.- For reverse traversal, starting from
size()and decrementing to 1, then accessing[i-1].
The C++ container class