How to use the fill_n() function in C++
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.
Syntax
void fill_n (Begin, End, Value);
Parameters
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.
Return value
fill_n() does not return a value.
Example
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.
Code
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;}
Explanation
-
In line 1, we import the required header file.
-
In line 4, we make a
mainfunction. -
In line 6, we declare a vector of
intdata 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
forloop 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++.