The ‘fill’ function assigns the value ‘val’ to all the elements in the range [begin, end), where ‘begin’ is the initial position and ‘end’ is the last position. NOTE : Notice carefully that ‘begin’ is included in the range but ‘end’ is NOT included. Below is an example to demonstrate ‘fill’ :
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector< int > vect(8);
fill(vect.begin() + 2, vect.end() - 1, 4);
for ( int i = 0; i < vect.size(); i++)
cout << vect[i] << " ";
return 0;
}
|
We can also use fill to fill values in an array.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
int arr[10];
fill(arr, arr + 10, 4);
for ( int i = 0; i < 10; i++)
cout << arr[i] << " ";
return 0;
}
|
Output:
4 4 4 4 4 4 4 4 4 4
Filling list in C++.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
list< int > ml = { 10, 20, 30 };
fill(ml.begin(), ml.end(), 4);
for ( int x : ml)
cout << x << " ";
return 0;
}
|
The time complexity of fill function: O(N)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
14 Mar, 2023
Like Article
Save Article