C++ fill() function
fill is used in array tofill all elements, quickly setting all elements to the same value.
fill is a member function of the container class, used tosets all elements in the container to a specified value. This is an O(n) operation requiring traversal of all elements.
fill is a shortcut for initializing or resetting array.
Word meaning: fill means 'fill', i.e., setting all elements to a specified value.
Basic syntax and parameters
fill is a member function of the container class and requires a fill value to be specified.
Syntax format
void fill(const T& value);
Parameter Description
- Parameters:
value - Type: Same as the container element type
- Description: The value to fill into all elements.
Function description
- Return Value:
void(no return value). - effect: Sets every element in the container to
value. - Note:
fillmodifies all elements in the container.
Example
Let us thoroughly master fill through a series of examples from simple to complex.
Example 1: Basic usage - filling with the same value
Example
#include
#include
int
main
(
)
{
std
::
array
<
int
,
5
numbers
=
{
1
,
2
,
3
,
4
,
5
};
std
::
cout
<<
"Before fill: "
;
for
(
int
n
:
numbers
)
{
std
::
cout
<<
n
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
// Fill all elements with 0
numbers.
fill
(
0
)
;
std
::
cout
<<
"After fill: "
;
for
(
int
n
:
numbers
)
{
std
::
cout
<<
n
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
填充前: 1 2 3 4 5
填充后: 0 0 0 0 0
Code analysis:
numbers.fill(0)sets all 5 elements to 0.- This is an O(n) operation that traverses all elements and assigns values.
Example 2: Initializing to a specific value
Use fill can quickly initialize array.
Example
#include
#include
#include
int
main
(
)
{
// Create and initialize to -1
std
::
array
<
int
,
10
scores;
scores.
fill
(
1
)
;
std
::
cout
<<
"Initialized to -1: "
;
for
(
int
s
:
scores
)
{
std
::
cout
<<
s
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
// Create and initialize to an empty string
std
::
array
<
std
::
string
,
3
names
;
names.
fill
(
"Unknown"
)
;
std
::
cout
<<
"Initialized to Unknown: "
;
for
(
const
auto
&
n
:
names
)
{
std
::
cout
<<
n
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
初始化为 -1: -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
初始化为 Unknown: Unknown Unknown Unknown
Code analysis:
fillcan be used to quickly initialize an array of any type.- For integers, 0 or -1 is commonly used; for strings, an empty string or a specific placeholder is commonly used.
The C++ container class