fill in C++ STL
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’ :
// C++ program to demonstrate working of fill() #include <bits/stdc++.h> using namespace std; int main() { vector<int> vect(8); // calling fill to initialize values in the // range to 4 fill(vect.begin() + 2, vect.end() - 1, 4); for (int i = 0; i < vect.size(); i++) cout << vect[i] << " "; return 0; } |
chevron_right
filter_none
Output:
0 0 4 4 4 4 4 0
We can also use fill to fill values in an array.
// C++ program to demonstrate working of fill() #include <bits/stdc++.h> using namespace std; int main() { int arr[10]; // calling fill to initialize values in the // range to 4 fill(arr, arr + 10, 4); for (int i = 0; i < 10; i++) cout << arr[i] << " "; return 0; } |
chevron_right
filter_none
Output:
4 4 4 4 4 4 4 4 4 4
Filling list in C++.
// C++ program to demonstrate working of fill() #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; } |
chevron_right
filter_none
Output:
4 4 4
Recommended Posts:
- C++ Program that will fill whole memory
- fill() function in C++ STL with examples
- fill() and fill_n() functions in C++ STL
- array::fill() and array::swap() in C++ STL
- Minimum cells to be flipped to get a 2*2 submatrix with equal elements
- Nested Loops in C++ with Examples
- _Find_first() function in C++ bitset with Examples
- _Find_next() function in C++ bitset with Examples
- Left-Right traversal of all the levels of N-ary tree
- Difference between Iterators and Pointers in C/C++ with Examples
- ostream::seekp(pos) method in C++ with Exmaples
- Default Methods in C++ with Examples
- C++ Tutorial
- Hello World Program : First program while learning Programming
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


