In this shot, we will discuss how to use the fill_n()
function. The fill_n()
function is available in the <bits/stdc++.h>
header file in C++ and is used to fill values up to the first n positions from a starting position.
void fill_n (Begin, End, Value);
The fill_n()
function takes the following parameters:
Begin
: Iterator pointing to the beginning of the position from which the values need to be filled.End
: Number of positions up until which the value needs to be filled.Value
: The value to be filled.fill_n()
does not return a value.
Let’s understand with the help of an example:
We have a vector of size 7.
We use the fill_n(vector.begin,4,3)
function to fill the value (3) up to the 4th position.
The vector is 3 3 3 3 0 0 0 after we use the fill_n()
function.
Let’s look at the code snippet below.
#include <bits/stdc++.h> using namespace std; int main() { vector<int> v(7); fill_n(v.begin(), 4, 5); for (int i = 0; i < v.size(); i++) cout << ' ' << v[i]; cout << '\n'; return 0; }
In line 1, we import the required header file.
In line 4, we make a main
function.
In line 6, we declare a vector of int
data type of size 7.
In line 7, we use the fill_n()
function to fill the value 5 from the beginning of the vector to the 4th position.
In lines 9 and 10, we use the for
loop to access the elements of the vector and display them as a result.
In this way, we can use the fill_n()
function in C++.
RELATED TAGS
CONTRIBUTOR
View all Courses